Freitag, 23. Januar 2009

How to create rotated axis labels in R

R FAQ: "To rotate axis labels (using base graphics), you need to use text(), rather than mtext(), as the latter does not support par('srt').


## Increase bottom margin to make room for rotated labels
par(mar = c(7, 4, 4, 2) + 0.1)
## Create plot with no x axis and no x axis label
plot(1 : 8, xaxt = 'n', xlab = '')
## Set up x axis with tick marks alone
axis(1, labels = FALSE)
## Create some text labels
labels <- paste('Label', 1:8, sep = ' ')
## Plot x axis labels at default tick marks
text(1:8, par('usr')[3] - 0.25, srt = 45, adj = 1,
labels = labels, xpd = TRUE)
## Plot x axis label at line 6 (of 7)
mtext(1, text = 'X Axis Label', line = 6)


When plotting the x axis labels, we use srt = 45 for text rotation angle, adj = 1 to place the right end of text at the tick marks, and xpd = TRUE to allow for text outside the plot region. You can adjust the value of the 0.25 offset as required to move the axis labels up or down relative to the x axis. See ?par for more information.

Also see Figure 1 and associated code in Paul Murrell (2003), “Integrating grid Graphics Output with Base Graphics"