仅在facet_wrap条文本中显示一个变量标签? [英] Only show one variable label in facet_wrap strip text?

查看:145
本文介绍了仅在facet_wrap条文本中显示一个变量标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rggplot2软件包中的facet_wrap()绘制多个图形.当使用多个变量进行分面时,结果在带状文本中包括两个标签.如何删除一个?

I am plotting multiple graphs using facet_wrap() from the ggplot2 package in R. When facetting by multiple variables, the result includes both labels in the strip text. How can I remove one?

在这个来自mpg数据集的玩具示例中,如何仅保留cyl标签?谢谢

In this toy example from the mpg dataset, how to keep the cyl labels only? Thanks

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(c("cyl", "drv"))

推荐答案

与此有关的最大问题是@aelwan提到了多个地块将具有相同的条带标签,但不相同.忽略这个问题,我认为最好的方法是在cyldrv之间创建一个新的交叉变量.

The biggest concern with this is as @aelwan mentioned several plots will have the same strip labels but are not the same. Ignoring this issue, I believe the best way to proceed is by creating a new cross variable between cyl and drv.

因此,如果您只需要一行用于标签,则可以例如:

So if you just want one row for the strip labels you can for example:

ggplot(mpg %>% mutate(cyl_drv = paste0(cyl, '-', drv)), aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ cyl_drv)

然后,您可以根据需要更改标签:

You can then change the labels if you need as follows:

ggplot(mpg %>% mutate(cyl_drv = paste0(cyl, '-', drv)), aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ cyl_drv, labeller = as_labeller(c(`4-4`="4", `4-f`="4", `5-f`=5, `6-4`=6, `6-f`=6, `6-r`=6, `8-4`=8, `8-f`=8, `8-r`=8)))

另一种(当然不是很好)的更改方法如下(我怀疑还有更好的方法可以做到):

Another (admittedly not great) way to change it is as follows (which I suspect there is a better way to do):

library(ggplot2)
library(ggExtra)
library(grid)
library(gtable)
gg <- ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ cyl * drv)

g1 <- ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ cyl)

gtab <- ggplotGrob(gg)

gtab$grobs[[47]] <- ggplotGrob(g1)$grobs[[23]]
gtab$grobs[[48]] <- ggplotGrob(g1)$grobs[[23]]
gtab$grobs[[49]] <- ggplotGrob(g1)$grobs[[23]]
gtab$grobs[[50]] <- ggplotGrob(g1)$grobs[[22]]
gtab$grobs[[51]] <- ggplotGrob(g1)$grobs[[22]]
gtab$grobs[[52]] <- ggplotGrob(g1)$grobs[[22]]
gtab$grobs[[53]] <- ggplotGrob(g1)$grobs[[24]]
gtab$grobs[[54]] <- ggplotGrob(g1)$grobs[[24]]
gtab$grobs[[55]] <- ggplotGrob(g1)$grobs[[25]]

grid.draw(gtab)

这篇关于仅在facet_wrap条文本中显示一个变量标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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