Only show one variable label in facet_wrap strip text?

空扰寡人 提交于 2020-01-24 19:18:07

问题


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?

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


回答1:


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)


来源:https://stackoverflow.com/questions/45114850/only-show-one-variable-label-in-facet-wrap-strip-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!