Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating text of secondary axis labels

Tags:

r

ggplot2

I'm taking advantage of the recently added feature of secondary axis labels in ggplot2. I'd like to rotate just the secondary axis but have been unable to find documentation or work out how to do this.

Its simple enough to rotate all text using...

ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
    geom_point() +
    scale_x_continuous(name = 'Bottom Axis',
                       sec.axis = sec_axis(trans = ~ .,
                                           name  = 'Top Axis',
                                           breaks = c(2:5),
                                           labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five'))) +
## Rotate text of x-axis
    theme(axis.text.x = element_text(angle = 90))

Example dual Axis plot with both axes labels rotated Its not mentioned in any of the documentation I've read (e.g. scale_continuous and themes) how to achieve rotating of just one axis.

My motivation for requiring this is that some of the labels I wish to apply to my data are long and overlap when placed horizontally, by rotating them I can avoid this, but I wish to retain the horizontal orientation on the bottom axis.

like image 224
slackline Avatar asked Dec 13 '16 10:12

slackline


People also ask

How do you rotate a multi level category label in Excel?

On the Format tab, in the Current Selection group, clickFormat Selection. On the Alignment tab, under Text Layout, click the position that you want in theVertical alignment box. To change the orientation of the text, click the position that you want in theText Direction box.


1 Answers

As long as you have a relatively current version of ggplot2, you can use axis.text.x.top:

ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
  geom_point() +
  scale_x_continuous(
    name = 'Bottom Axis',
    sec.axis = sec_axis(
      trans = ~ .,
      name  = 'Top Axis',
      breaks = 2:5,
      labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five')
    )
  ) +
  ## Rotate text of x-axis
  theme(axis.text.x.top = element_text(angle = 45, hjust = 0))

enter image description here

like image 198
Axeman Avatar answered Sep 22 '22 06:09

Axeman