Rotate direction of title of secondary axis

Viewed 789

I need to put an additional right-hand y axis on a graph. I have managed to do that in ggplot using the code below. But the text direction for that axis is opposite to that for the primary y axis. I have been asked to make the text directions the same. I have searched for instructions for that in the ggplot help and online but nowhere can I find anything about how to control the direction of a secondary axis title (tick labels yes, titles no).

I would be grateful if anybody can tell me how to do this. Thank you.

tbbl <- tibble(ltrs = letters,
               nums = rnorm(26)) %>%
  mutate(rownum = row_number()) %>%
  mutate(colr = factor(.$rownum %% 2, levels = 0:1) )

gx <- ggplot(data = tbbl, aes(x = rownum)) +
  geom_col(aes(y = nums, colour = colr, fill = colr)) +
  scale_y_continuous(sec.axis = sec_axis(~ . / 4.184, 
                                         name = 'Long title that my client finds hard to read if aligned the default way')) +
  labs(x = 'title for x axis', y = 'title for y axis')
print(gx)
1 Answers

You can set the angle of the secondary y axis title via theme option axis.title.y.right:

library(ggplot2)
library(dplyr)

tbbl <- tibble(ltrs = letters,
               nums = rnorm(26)) %>%
  mutate(rownum = row_number()) %>%
  mutate(colr = factor(.$rownum %% 2, levels = 0:1) )

ggplot(data = tbbl, aes(x = rownum)) +
  geom_col(aes(y = nums, colour = colr, fill = colr)) +
  scale_y_continuous(sec.axis = sec_axis(~ . / 4.184, 
                                         name = 'Long title that my client finds hard to read if aligned the default way')) +
  labs(x = 'title for x axis', y = 'title for y axis') +
  theme(axis.title.y.right = element_text(angle = 90))

Related