问题
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