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

在ggplot的右侧facet_wrap面板添加左侧样式y轴实线

解决ggplot分面后右侧面板无y轴实线的问题

要让右侧面板也显示和左侧一致的y轴实线,最简单的方法是在theme中显式启用axis.line.y.right元素,具体修改如下:

修改后的完整代码

library(ggplot2)
library(ggh4x)

df <- expand.grid(
  var = c("v1","v2"),
  outcome = c("OutcomeA","OutcomeB"),
  model_f = c("m1","m2"),
  KEEP.OUT.ATTRS = FALSE,
  stringsAsFactors = FALSE
)

df$coef     <- c(-0.05, 0.02,  0.08, 0.10,  -0.02, 0.04,  0.12, 0.15)
df$ci_lower <- c(-0.12,-0.04,  0.02, 0.03,  -0.10,-0.02,  0.05, 0.09)
df$ci_upper <- c( 0.02, 0.08,  0.14, 0.18,   0.06, 0.10,  0.20, 0.22)

ggplot(df, aes(x = coef, y = var, group = model_f, color = interaction(outcome, model_f))) +
  geom_vline(xintercept = 0, linetype = "dotted") +
  geom_point(position = position_dodge(width = 0.5), size = 3) +
  geom_errorbarh(aes(xmin = ci_lower, xmax = ci_upper),
                 position = position_dodge(width = 0.5),
                 height = 0, linewidth = 1) +
  facet_wrap2(~ outcome, ncol = 2) +
  theme_classic() +
  theme(
    panel.grid = element_blank(),
    legend.position = "none",
    # 启用右侧面板的y轴实线,继承theme_classic的样式
    axis.line.y.right = element_line()
  )

原理说明

theme_classic()默认只显示左侧面板的y轴实线,右侧面板的axis.line.y.right元素被设为element_blank()隐藏了。通过显式将其设置为element_line(),就能让右侧面板生成和左侧样式完全一致的y轴实线,实现对称的轴线条效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 09:32:48