Plot axes with customized labels
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
How to modify axis labels is a FAQ for (almost) all R users.
This short post try to give a simple but exhaustive reply to this question.
First of all, data are generated.
dat = data.frame( label = sample(c(1, 2, 3), 150, replace = TRUE), val = rgamma(150, 50) ) |
A boxplot of the numeric variable val
can be generated for each group.
boxplot(dat$val ~ dat$label) |
The simplest way to add a label for groups is treating the label
variable as a factor. This is the best choice also from a logical point of view.
dat$label = factor( dat$label, levels = 1:3, labels = c("First", "Second", "Third") ) |
Wow! Now the plot show the group names.
boxplot(dat$val ~ dat$label) |
If labels change, factor can be modified in a one line.
levels(dat$label) = c( "My First Group has a very long name", "My Second Group is a little bit more long", "The third one is as long as the first" ) |
And again, my plot!
boxplot(dat$val ~ dat$label) |
The labels are too long and the second one doesn't appear. Labels may be rotated, using the las
parameter. This argument specifies the style of axis labels. It can assume one of the following: 0 (always parallel to the axis, which is the default), 1 (always horizontal), 2 (always perpendicular to the axis), 3 (always vertical).
boxplot(dat$val ~ dat$label, las = 3) |
Labels have been rotated, but labels go outside the margin and disappears. Bottom margin should be increased. This can be done using the mar
argument of the par()
function. The default is par(mar = c(5,4,4,2))
which means that there are 5 lines at the bottom, 4 lines on the left, 4 lines in the top and 2 lines on the right. The bottom margin can be increased to 20 lines.
op0 = par() # Get current graphical parameters op1 = op0$mar # Get current margins in lines op1[1] = 20 # Modify bottom margins to 20 (lines) op1 # View bottom margins in lines |
## [1] 20.0 4.1 4.1 2.1 |
If you want to specify margins in inches, use par(mai = c(bottom, left, top, right)
.
Now I obtained the plot I was looking for!
par(mar = op1) boxplot(dat$val ~ dat$label, las = 3) |
Next article will show how to manage axis, add/remove ticks and modify labels out of data structure, i.e. without modify factors.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.