如何删除2路facet_grid中的空面板?

pb3s4cty  于 2023-05-20  发布在  其他
关注(0)|答案(2)|浏览(87)

我想从ggplot 2路facet_grid中删除整个面板。我从this问题中得到了一些线索。下面是带有示例数据的代码

library(ggplot2)
library(ggh4x)

df <- data.frame(x=rnorm(80),y=rnorm(80),
                  col=rep(c(" ", "B","C"," ","B","C","B","C"),each=10),
                  row=rep(c("a","a","a","b","b","b","c","c"),each=10))

ggplot(data=df,aes(x=x,y=y))+
  geom_point()+
  facet_grid2(row~col, scales = "free", independent = "all")

我想拆下左边的嵌板。如何才能做到这一点?

3ks5zfa0

3ks5zfa01#

从您的评论中注意到,预先设置数据集的子集不是您的选择,因此这里有一个后期制作方法:

# create plot
p <- ggplot(data=df,aes(x=x,y=y))+
  geom_point()+
  facet_grid2(row~col, scales = "free", independent = "all")

# convert to grob
gp <- ggplotGrob(p)

# check which are the columns of the gtable to strip out
# (for the example, we want to strip out content from cols 4-5)
gp                             # examine layout in console
gtable::gtable_show_layout(gp) # examine layout in viewer

# strip them out
gp <- gp %>%
  cowplot::gtable_remove_grobs(names = gp$layout %>% 
                                 filter(r %in% 4:5) %>% 
                                 pull(name)) %>%
  cowplot::gtable_squash_cols(cols = 4:5)

# plot the result
plot(gp)

数据:

set.seed(123)
df <- data.frame(x=rnorm(80),y=rnorm(80),
                 col=rep(c(" ", "B","C"," ","B","C","B","C"),each=10),
                 row=rep(c("a","a","a","b","b","b","c","c"),each=10))
esyap4oy

esyap4oy2#

一种方法是使用subset()

library(ggplot2)
library(ggh4x)

df %>%
  subset(!(row == "a" & col == " ")) %>%
  ggplot(aes(x=x,y=y)) +
  geom_point() +
  facet_grid2(row~col, scales = "free", independent = "all")

相关问题