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

ggplot facet_grid按outcome_type2设置自由Y轴及分面间距调整

解决方案:按分组设置独立Y轴并调整分面间距

需求1:按outcome_type2分组使用独立Y轴范围

原生ggplot2的facet_grid无法直接实现按组共享Y轴、组间独立Y轴的效果,这里提供两种可行方案:

方案1:使用ggh4x包的facet_grid2(保持单图结构)

ggh4x扩展了ggplot的分面能力,支持嵌套分组并共享轴范围:

# 安装并加载依赖包
install.packages("ggh4x")
library(ggplot2)
library(ggh4x)
library(forcats)

# 预设分面显示顺序
dtest$outcome_type <- fct_relevel(dtest$outcome_type, "CT", "CI", "CE", "FZ", "MZ", "PSS", "CSS")
dtest$outcome_type2 <- fct_relevel(dtest$outcome_type2, "C", "Z", "SS")

# 绘图代码
ggplot(dtest, aes(x = var2, y = avg2, fill = var2)) +
  geom_bar(stat = "identity", width = 1) +
  # 嵌套分面:先按outcome_type2分组,再按outcome_type细分
  facet_grid2(wave ~ outcome_type2 + outcome_type,
              scales = "free_y",       # 组间Y轴独立适配数据范围
              space = "free_y",        # 组间Y轴高度自适应
              strip = strip_nested(bleed = TRUE)) +  # 合并分组标题,减少冗余
  theme_minimal() +
  theme(
    legend.position = "none",
    # 调整列间距:同组内紧凑,组间加大空白区分
    panel.spacing.x = unit(c(0.1, 0.1, 1, 0.1, 1, 0.1), "cm"),
    strip.background.x = element_rect(fill = "#f0f0f0", color = NA)
  )
  • 效果:C/Z/SS三组各自使用匹配自身数据范围的Y轴,同组内子面板共享Y轴,彻底解决数据压缩问题。

方案2:使用patchwork拼接子图(灵活性更高)

将数据按outcome_type2拆分,分别绘制子图后拼接,完全独立控制每组的Y轴:

install.packages("patchwork")
library(ggplot2)
library(patchwork)
library(forcats)

# 拆分数据为三组
c_group <- subset(dtest, outcome_type2 == "C")
z_group <- subset(dtest, outcome_type2 == "Z")
ss_group <- subset(dtest, outcome_type2 == "SS")

# 绘制C组子图
plot_c <- ggplot(c_group, aes(x = var2, y = avg2, fill = var2)) +
  geom_bar(stat = "identity", width = 1) +
  facet_grid(wave ~ fct_relevel(outcome_type, "CT", "CI", "CE"), 
             scales = "free_y", space = "free_y") +
  theme_minimal() +
  theme(legend.position = "none") +
  ggtitle("C组")

# 绘制Z组子图
plot_z <- ggplot(z_group, aes(x = var2, y = avg2, fill = var2)) +
  geom_bar(stat = "identity", width = 1) +
  facet_grid(wave ~ fct_relevel(outcome_type, "FZ", "MZ"), 
             scales = "free_y", space = "free_y") +
  theme_minimal() +
  theme(legend.position = "none") +
  ggtitle("Z组")

# 绘制SS组子图
plot_ss <- ggplot(ss_group, aes(x = var2, y = avg2, fill = var2)) +
  geom_bar(stat = "identity", width = 1) +
  facet_grid(wave ~ fct_relevel(outcome_type, "PSS", "CSS"), 
             scales = "free_y", space = "free_y") +
  theme_minimal() +
  theme(legend.position = "none") +
  ggtitle("SS组")

# 拼接子图,设置组间间距和宽度比例
plot_c + plot_z + plot_ss +
  plot_layout(nrow = 1, widths = c(3, 2, 2), gap = unit(1, "cm"))
  • 效果:每组拥有完全独立的Y轴,组间空白可通过gap参数精准控制,子图宽度也能按需调整。

需求2:调整分面列间距

  • 方案1中通过panel.spacing.x手动设置每列的间距,数组中对应组间的位置(第3、5个值)设置更大单位,实现同组紧凑、组间留白的效果。
  • 方案2中通过patchwork的gap参数直接控制组间空白,操作更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:31:18