Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 switchargument 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.

like image 671
roming Avatar asked Nov 08 '16 10:11

roming


People also ask

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data. If you have only one variable with many levels, try facet_wrap() .

How do you change a facet wrap label?

Facet labels can be modified using the option labeller , which should be a function. In the following R code, facets are labelled by combining the name of the grouping variable with group levels. The labeller function label_both is used.

How can I change my facet order?

You can use the following basic syntax to specify the order of facets in ggplot2: p + facet_grid(~factor(my_variable, levels=c('val1', 'val2', 'val3', ...))) The following example shows how to use this syntax in practice.


1 Answers

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

library(tidyverse) library(reshape2)  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.left = element_text(angle = 0)) 

Created on 2020-03-15 by the reprex package (v0.3.0)

Note that strip.text.y.left was added in ggplot2 3.3.0. For earlier versions, you need to write strip.text.y = element_text(angle = 180).

like image 168
joel.wilson Avatar answered Sep 19 '22 00:09

joel.wilson