在ggplot2中旋转切换的构面标签facet_grid [英] Rotate switched facet labels in ggplot2 facet_grid

查看:104
本文介绍了在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)

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

这篇关于在ggplot2中旋转切换的构面标签facet_grid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆