I need some help with axis labels in base R plotting, thanks in advance for any guidance!
What I need:
In R base plot() I would like to rotate my axis(3, ...) label to -90 degrees to get the following output:
(note that I have rotated the pic outside R)
Why I need it (big picture):
I am using labcurve for curve annotation and strangely enough for my data the annotation results are visually waay better if applied to the -90 degree rotated graph. After running labcurve I can rotate the resulting R-generated PDF back 90 degrees in LaTeX.
What I have tried:
#1
I know that this is governed by the las option in par with the following options:
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.
However, these four options available only cover the two angles 0 and 90 degrees as either of the following:
plot(x=c(0,10), y=c(0,1), type='n', xlab='',ylab='', axes=FALSE)
lines(x=c(0,7,7,10), y=c(0,0.33,0.67,1))
axis(2, at=c(0,1), labels=c('',''), las=2)
xlabels <- c('0','10')
axis(3, at=c(0,10), labels=xlabels, las=0)
or
axis(3, at=c(0,10), labels=xlabels, las=1)
axis(3, at=c(0,10), labels=xlabels, las=2)
or
axis(3, at=c(0,10), labels=xlabels, las=3)
#2:
One could think of str but according to the doc:
Note that string/character rotation via argument srt to par does not
affect the axis labels.
Thanks again!
The general procedure for creating rotated axis labels is described in R FAQ 7.27. Here's a modified example which hopefully suits your needs.
# some toy data
x <- c(0, 2, 6, 10)
y <- sample(1:4)
# Increase top margin to make room for rotated labels
par(mar = c(5, 4, 7, 2) + 0.1)
# Create plot without axis or labels
plot(x, y, type = "l", axes = FALSE, xlab = "", ylab = "")
# positions for tick marks
atx <- range(x)
aty <- range(y)
# x axis without labels
axis(side = 3, at = atx, labels = FALSE)
# y axis without labels
axis(side = 2, at = aty, labels = FALSE)
# add -90 rotated x axis labels
text(x = atx, y = par("usr")[4] + 0.25, srt = -90, adj = 1,
labels = atx, xpd = TRUE)
Related
I am trying to get the x axis labels to be rotated 45 degrees on a barplot with no luck. This is the code I have below:
barplot(((data1[,1] - average)/average) * 100,
srt = 45,
adj = 1,
xpd = TRUE,
names.arg = data1[,2],
col = c("#3CA0D0"),
main = "Best Lift Time to Vertical Drop Ratios of North American Resorts",
ylab = "Normalized Difference",
yaxt = 'n',
cex.names = 0.65,
cex.lab = 0.65)
use optional parameter las=2 .
barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)
EDITED ANSWER PER DAVID'S RESPONSE:
Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot and do a little tweaking up and down. Here's an example with the mtcars data set:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
xaxt = "n", # Do not plot the default labels
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
You can use ggplot2 to rotate the x-axis label adding an additional layer
theme(axis.text.x = element_text(angle = 90, hjust = 1))
In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:
... arguments to be passed to/from other methods. For the default method these can
include further arguments (such as axes, asp and main) and graphical
parameters (see par) which are passed to plot.window(), title() and axis.
In the documentation of graphical parameters (documentation of par) we can see:
las
numeric in {0,1,2,3}; the style of axis labels.
0:
always parallel to the axis [default],
1:
always horizontal,
2:
always perpendicular to the axis,
3:
always vertical.
Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.
That is why passing las=2 makes the labels perpendicular, although not at 45°.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
I am trying to get the x axis labels to be rotated 45 degrees on a barplot with no luck. This is the code I have below:
barplot(((data1[,1] - average)/average) * 100,
srt = 45,
adj = 1,
xpd = TRUE,
names.arg = data1[,2],
col = c("#3CA0D0"),
main = "Best Lift Time to Vertical Drop Ratios of North American Resorts",
ylab = "Normalized Difference",
yaxt = 'n',
cex.names = 0.65,
cex.lab = 0.65)
use optional parameter las=2 .
barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)
EDITED ANSWER PER DAVID'S RESPONSE:
Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot and do a little tweaking up and down. Here's an example with the mtcars data set:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
xaxt = "n", # Do not plot the default labels
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
You can use ggplot2 to rotate the x-axis label adding an additional layer
theme(axis.text.x = element_text(angle = 90, hjust = 1))
In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:
... arguments to be passed to/from other methods. For the default method these can
include further arguments (such as axes, asp and main) and graphical
parameters (see par) which are passed to plot.window(), title() and axis.
In the documentation of graphical parameters (documentation of par) we can see:
las
numeric in {0,1,2,3}; the style of axis labels.
0:
always parallel to the axis [default],
1:
always horizontal,
2:
always perpendicular to the axis,
3:
always vertical.
Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.
That is why passing las=2 makes the labels perpendicular, although not at 45°.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
This question already has answers here:
How can I plot with 2 different y-axes?
(6 answers)
Closed 6 years ago.
i'm having troubles in a multi axis barplot. I have an X,Y axis with bars and dots in the same graph. The point is that I have to shown both of them in different scales
While I can shown both (bars and dots) correctly, the problem comes when I try to set different scales in left and right axis. I dont know how to change the aditional axis scale, and how to bind the red dots to the right axis, and the bars to the left one.
This is my code and what I get:
labels <- value
mp <- barplot(height = churn, main = title, ylab = "% churn", space = 0, ylim = c(0,5))
text(mp, par("usr")[3], labels = labels, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=.9)
# Population dots
points(popul, col="red", bg="red", pch=21, cex=1.5)
# Churn Mean
media <- mean(churn)
abline(h=media, col = "black", lty=2)
# Population scale
axis(side = 4, col= "red")
ylim= c(0,50)
ylim= c(0,5)
What I want is to have left(grey) axis at ylim=c(0,5) with the bars bound to that axis. And the right(red) axis at ylim=c(0,50) with the dots bound to that axis...
The goal is to represent bars and points in the same graph with diferent axis.
Hope I explained myself succesfully.
Thanks for your assistance!
Here is a toy example. The only "trick" is to store the x locations of the bar centers and the limits of the x axis when creating the barplot, so that you can overlay a plot with the same x axis and add your points over the centers of the bars. The xaxs = "i" in the call to plot.window indicates to use the exact values given rather than expanding by a constant (the default behavior).
set.seed(1234)
dat1 <- sample(10, 5)
dat2 <- sample(50, 5)
par(mar = c(2, 4, 2, 4))
cntrs <- barplot(dat1)
xlim0 <- par()$usr[1:2]
par(new = TRUE)
plot.new()
plot.window(xlim = xlim0, ylim = c(0, 50), xaxs = "i")
points(dat2 ~ cntrs, col = "darkred")
axis(side = 4, col = "darkred")
I am trying to get the x axis labels to be rotated 45 degrees on a barplot with no luck. This is the code I have below:
barplot(((data1[,1] - average)/average) * 100,
srt = 45,
adj = 1,
xpd = TRUE,
names.arg = data1[,2],
col = c("#3CA0D0"),
main = "Best Lift Time to Vertical Drop Ratios of North American Resorts",
ylab = "Normalized Difference",
yaxt = 'n',
cex.names = 0.65,
cex.lab = 0.65)
use optional parameter las=2 .
barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)
EDITED ANSWER PER DAVID'S RESPONSE:
Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot and do a little tweaking up and down. Here's an example with the mtcars data set:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
xaxt = "n", # Do not plot the default labels
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
You can use ggplot2 to rotate the x-axis label adding an additional layer
theme(axis.text.x = element_text(angle = 90, hjust = 1))
In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:
... arguments to be passed to/from other methods. For the default method these can
include further arguments (such as axes, asp and main) and graphical
parameters (see par) which are passed to plot.window(), title() and axis.
In the documentation of graphical parameters (documentation of par) we can see:
las
numeric in {0,1,2,3}; the style of axis labels.
0:
always parallel to the axis [default],
1:
always horizontal,
2:
always perpendicular to the axis,
3:
always vertical.
Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.
That is why passing las=2 makes the labels perpendicular, although not at 45°.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
I have a plot that has $-amounts and dates on y and x axis respectively. Currently the dollar amounts range from $0-15 million. Something like this:
x <- rnorm(20)^2 * 1000000
plot(x)
R does stuff like '1.0e+07' instead of '10,000,000' and also orients the text vertically instead of horizontally.
My questions are:
1) how would I get the scale text to be horizontally oriented?
2) how would I get R to use 10MM instead of '10,000,000' or '1.0e+07'?
1) See the scipen option in ?options which is a penalty against the use of scientific notation. For better control, you need to plot the axis by hand with labels you want.
2) See las in ?par which controls to orientation crudely of axis labels.
For 1):
x <- rnorm(20)^2 * 10000000
layout(matrix(1:2, ncol = 2))
plot(x)
getOption("scipen")
opt <- options("scipen" = 20)
getOption("scipen")
plot(x)
options(opt)
layout(1)
which gives
To plot your own axis try
plot(x / 10000000, axes = FALSE)
axis(1)
pts <- pretty(x / 10000000)
axis(2, at = pts, labels = paste(pts, "MM", sep = ""))
box()
Which gives
Where we use pretty() to select pretty locations for the ticks just as R would and then add a custom axis. Notice how we suppress axis drawing in the plot() call and then add back the axes and the plot frame with calls to axis() and box().
For 2) combining with 1)
opt <- options("scipen" = 20)
op <- par(mar = c(5,7,4,2) + 0.1) ## extra margin to accommodate tick labs
x <- rnorm(20)^2 * 10000000
plot(x, las = 1, ylab = "") ## no y-axis label
title(ylab = "label", line = 5.5) ## need to plot the axis label
par(op)
options(opt)
Which gives
Notice how we use las in the plot() call, and we need to create some extra margin space to accommodate the tick labels. We also need to plot the label by hand otherwise R will stick it in amongst the tick labels.
For the custom axis labels, add the las = 1 to the axis() call:
op <- par(mar = c(5,5,4,2) + 0.1)
plot(x / 10000000, axes = FALSE, ylab = "")
axis(1)
pts <- pretty(x / 10000000)
axis(2, at = pts, labels = paste(pts, "MM", sep = ""), las = 1)
title(ylab = "my label", line = 4)
box()
par(op)
Which produces
Use axis with custom labels. First, divide your data by 1 million. And then create a series with the MM notation using paste()
y <-rnorm(20)^2 * 1000000 /1000000
x <-11:30
plot(x,y, yaxt="n")
my.axis <-paste(axTicks(2),"MM",sep="")
axis(2,at=axTicks(2), labels=my.axis)
The text is now horizontal. But if you run into a problem use, las=1 to force labels to be horizontal.
axis(2,at=axTicks(2), labels=my.axis, las=1)