3
set.seed(3)
y = rnorm(10)
x = seq(1, 10, 1)
plot(y ~ x)

enter image description here

Instead of the x-axis tick mark labels of 1, 2, 3, 4, 5, how can I add a custom label? Suppose I want tick mark 1 to be labeled as "This is a very long string 1", tick mark 2 to be labeled as "This is a very long string 2" ... etc. Since these labels are long, I'd like to set them at an angle (maybe 135 degrees or something like that) so that they're easy to read. How can I do this in R?

Adrian
  • 9,229
  • 24
  • 74
  • 132
  • See function `axis`, (`?axis`). –  Oct 09 '15 at 07:59
  • 1
    Possible duplicate of [R: Replace X-axis with own values](http://stackoverflow.com/questions/5182238/r-replace-x-axis-with-own-values) –  Oct 09 '15 at 08:00

1 Answers1

2

Instead of the x-axis tick mark labels of 1, 2, 3, 4, 5, how can I add a custom label? Suppose I want tick mark 1 to be labeled as "This is a very long string 1", tick mark 2 to be labeled as "This is a very long string 2" ... etc. Since these labels are long, I'd like to set them at an angle (maybe 135 degrees or something like that) so that they're easy to read. How can I do this in R?

You have two parts here, custom annotations on axis, and rotating them.

# First turn off axes on your plot:
plot(1:5, 1:5, axes=FALSE)
# now tell it that annotations will be rotated by 90* (see ?par)
par(las=2)
# now draw the first axis
axis(1, at=1:5, labels=c("yo ho ho and a bottle of rum", 2:5))
# add the other default embellishments, if you like
axis(2) #default way
box()

Notice that there won't be enough room on margins to fit a long text. So at some point you will need something like par(mar=c(6,1,1,1)). And then the par(las=foo) way can only rotate it by 90 degrees. I'm sure 135 degrees would be possible but don't know exactly how. (Maybe it would be easier with ggplot2 than base graphics.) And if you want to have your long label in 2 or 3 rows, then you can add \n's in the middle of the string eg. "yo ho ho\nand a bottle of \nrum".

lebatsnok
  • 6,329
  • 2
  • 21
  • 22
  • Thanks. Is there a way to put the beginning of the string next to the tick mark? Because right now "rum" is right next to the tick mark. I think it would be easier to read if "yo ho ho" were near the tickmark instead. In other words how can I rotate them 180 degrees? – Adrian Oct 09 '15 at 08:22
  • I'm sure there is but it would take more time to figure out than I have right now. A very quick way would be to use axis(3) (upper axis) instead of axis(1) – lebatsnok Oct 09 '15 at 08:28
  • actually you can have custom rotation, see http://www.r-bloggers.com/rotated-axis-labels-in-r-plots/ and http://www.hep.by/gnu/r-patched/r-faq/R-FAQ_78.html – lebatsnok Oct 09 '15 at 08:30
  • It's interesting that the srt argument hasn't been applied to `axis()` yet. I feel like that would be the most frequent spot that people would go to find it. – Badger Oct 09 '15 at 14:27