在ggplot2中旋转切换的构面标签facet_grid

问题描述:

我想使用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")

我使用ggplot2::facet_grid()switch参数使构面标签显示在y轴上,而不是显示在每个构面的顶部.问题是,构面标签是垂直绘制的,因此会被裁剪.有什么办法可以水平绘制构面标签?到目前为止,我发现的所有问题仅与旋转x轴标签有关,而与构面标签无关.

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.

您只需要添加theme()并在strip.text.y.left中指定角度.

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))

reprex软件包(v0.3.0)创建于2020-03-15 >

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

请注意,在ggplot2 3.3.0中添加了strip.text.y.left.对于早期版本,您需要编写strip.text.y = element_text(angle = 180).

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