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.

A boxplot of the numeric variable val can be generated for each group.

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.

Wow! Now the plot show the group names.

If labels change, factor can be modified in a one line.

And again, my plot!

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).

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.

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!

Next article will show how to manage axis, add/remove ticks and modify labels out of data structure, i.e. without modify factors.

Related Post