roming roming - 26 days ago 10
R Question

Rotate switched facet labels in ggplot2 facet_grid

I would like to plot some barplots on top of each other using facet_grid:

library(ggplot2)

df <- group_by(mpg, manufacturer) %>%
summarise(cty = mean(cty), hwy = mean(hwy)) %>%
ungroup()

df <- melt(df, id.vars = "manufacturer")

ggplot() +
geom_bar(data =df, aes(x = variable, y = value), stat = "identity") +
facet_grid(manufacturer ~ ., switch = "y")


I use the
switch
argument of
ggplot2::facet_grid()
to let the facet labels be displayed on the y-axis instead of on top of each facet. Problem is that the facet labels are plotted vertically and therefore cropped. Is there any way to plot the facet -labels horizontally? All the questions I found so far related to rotating the x-axis labels only, not the facet labels.

Answer

You just need to add the theme() and specify the angle in strip.text.y

library(ggplot2)
df <- group_by(mpg, manufacturer) %>%
  summarise(cty = mean(cty), hwy = mean(hwy)) %>%
  ungroup()

df <- melt(df, id.vars = "manufacturer")

ggplot() +
  geom_bar(data =df, aes(x = variable, y = value), stat = "identity") +
  facet_grid(manufacturer ~ ., switch = "y")+
 theme(strip.text.y = element_text(angle = 180))
Comments