Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating x-axis labels and changing theme in ggplot2

Tags:

r

ggplot2

Is there a way to rotate the x-axis labels in a ggplot plot AND change the theme at the same time?

If I do this, I can rotate the x-axis labels:

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

But if I add a theme, the rotations won't work:

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  theme_minimal()

I tried adding the rotation within the theme_minimal() function, but that didn't work either.

Thanks.

like image 870
GabrielMontenegro Avatar asked Dec 06 '22 10:12

GabrielMontenegro


2 Answers

That's because of the order: theme_minimal being after theme overrides the latter. Using

ggplot(ToothGrowth, aes(x = dose, y = len)) + 
  geom_boxplot() + theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

gives

enter image description here

like image 140
Julius Vainora Avatar answered Dec 07 '22 22:12

Julius Vainora


The theme theme_minimal changes a lot of things including the changes you made with theme. So that you should do it in the other way:

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot()
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
like image 31
Pop Avatar answered Dec 07 '22 22:12

Pop