You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除ggplot双向facet_grid中的空白面板?

移除ggplot双向facet_grid中的空白面板

方案一:过滤无关分组(若不需要col为空格的面板)

如果col列中的空格分组是多余的,直接过滤掉对应行即可消除空面板:

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

# 过滤col为空格的行
df_filtered <- df[df$col != " ", ]

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

方案二:保留部分分组,用拼接实现非对齐布局(若需要保留row=a/b的空格面板)

facet_grid是严格网格布局,每行必须保持相同列数,无法单独移除某一行的空面板。可以用patchwork包将不同行的图单独绘制后拼接,实现每行列数独立:

library(ggplot2)
library(ggh4x)
library(patchwork)

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

# 分别绘制每行的子图
p_a <- ggplot(df[df$row == "a", ], aes(x=x,y=y)) +
  geom_point() +
  facet_grid2(.~col, scales = "free", independent = "all") +
  ggtitle("a") +
  theme(plot.title = element_text(hjust = 0.5))

p_b <- ggplot(df[df$row == "b", ], aes(x=x,y=y)) +
  geom_point() +
  facet_grid2(.~col, scales = "free", independent = "all") +
  ggtitle("b") +
  theme(plot.title = element_text(hjust = 0.5))

p_c <- ggplot(df[df$row == "c", ], aes(x=x,y=y)) +
  geom_point() +
  facet_grid2(.~col, scales = "free", independent = "all") +
  ggtitle("c") +
  theme(plot.title = element_text(hjust = 0.5))

# 垂直拼接三个子图
p_a / p_b / p_c

内容的提问来源于stack exchange,提问作者UseR10085

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:05:40