英文:
How to remove empty panel in 2-way facet_grid?
问题
我想要移除 ggplot
2-way facet_grid
中的整个面板。我从这里这个问题中获取了一些启示。这是带有示例数据的代码
库(ggplot2)
库(ggh4x)
df <- 数据框架(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")
我想移除左侧面板。应该如何操作?
英文:
I want to remove the whole panel from ggplot
2-way facet_grid
. I have taken some lead from this question. Here is the code with example data
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")
I want to remove the left panel. How can it be done?
答案1
得分: 3
以下是您要翻译的内容:
根据您的评论,事先对数据集进行子集处理对您不是一个选项,所以这里是一种后期处理方法:
# 创建绘图
p <- ggplot(data=df,aes(x=x,y=y))+
geom_point()+
facet_grid2(row~col, scales = "free", independent = "all")
# 转换为grob对象
gp <- ggplotGrob(p)
# 检查要删除的gtable列
# (在此示例中,我们要删除列4到5的内容)
gp # 在控制台中查看布局
gtable::gtable_show_layout(gp) # 在查看器中查看布局
# 删除它们
gp <- gp %>%
cowplot::gtable_remove_grobs(names = gp$layout %>%
filter(r %in% 4:5) %>%
pull(name)) %>%
cowplot::gtable_squash_cols(cols = 4:5)
# 绘制结果
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))
<details>
<summary>英文:</summary>
Noted from your comment that subsetting the dataset beforehand isn't an option for you, so here's a post-production approach:
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)
[![result][1]][1]
data:
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))
[1]: https://i.stack.imgur.com/eSXoi.png
</details>
# 答案2
**得分**: 2
One way is to use `subset()`:
```R
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论