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

如何用ggplot2的geom_linerange绘制不重叠的两组置信区间?

用ggplot2实现双估计量置信区间并排展示

要解决geom_linerange导致区间重叠的问题,核心是给同组内的两个估计量的x轴位置加微小偏移,让它们错开排列。下面用示例代码演示完整流程:

步骤1:准备示例数据

先构造包含分组、两个估计量及其置信区间的数据集:

library(tidyverse)

# 模拟数据
set.seed(123)
df <- tibble(
  group = rep(c("Group A", "Group B", "Group C"), each = 2),
  estimator = rep(c("Estimator 1", "Estimator 2"), 3),
  mean_val = rnorm(6, 5, 1),
  ci_low = mean_val - 0.8,
  ci_high = mean_val + 0.8
)

步骤2:给x轴位置添加偏移

把分组转成数值后,给每个估计量加减固定偏移(比如0.1),让同组的两个区间错开:

df <- df %>%
  mutate(
    group_num = as.numeric(factor(group)),
    x_pos = ifelse(estimator == "Estimator 1", group_num - 0.1, group_num + 0.1)
  )

步骤3:用ggplot绘制并排置信区间

用geom_linerange画区间,geom_point标记均值,最后调整x轴标签和样式:

ggplot(df, aes(x = x_pos, y = mean_val, color = estimator)) +
  # 绘制置信区间
  geom_linerange(aes(ymin = ci_low, ymax = ci_high), linewidth = 1.2) +
  # 绘制均值点
  geom_point(size = 3) +
  # 调整x轴标签,对应原分组
  scale_x_continuous(
    breaks = unique(df$group_num),
    labels = unique(df$group)
  ) +
  # 添加坐标轴标题和主题
  labs(
    x = "分组",
    y = "估计值",
    color = "估计量"
  ) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    legend.position = "top"
  )

补充说明

  • 如果偏好用geom_errorbar(带短横的区间),直接替换geom_linerange即可,参数完全兼容。
  • 偏移量可以根据图表宽度调整,比如0.08或0.12,保证区间不重叠且视觉协调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:25:08