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

如何在ggplot中绘制OLS估计值的置信区间

为OLS估计值添加置信区间的解决方案

问题原因

你之前的尝试错误在于geom_hline不支持yinterceptmin/yinterceptmax这类参数,该图层仅用于绘制单一y值的水平线,无法直接展示置信区间。以下是两种可行的实现方式:


方法一:绘制上下两条虚线表示置信区间

通过额外添加两条geom_hline分别表示OLS估计值的置信区间上下限,用虚线样式区分:

ggplot(data = d1, aes(
  x = tau, y = Value,
  ymin = Value - Std..Error,
  ymax = Value + Std..Error
)) +
  geom_ribbon(alpha = 0.5) +
  geom_line(color = "blue") +
  labs(x = "Quantiles", y = "xyz") +
  # OLS估计值的红色实线
  geom_hline(data = d2, aes(yintercept = Estimate), color = "red", linewidth = 1) +
  # 置信区间下限的红色虚线
  geom_hline(data = d2, aes(yintercept = Estimate - `Std. Error`), color = "red", linetype = "dashed") +
  # 置信区间上限的红色虚线
  geom_hline(data = d2, aes(yintercept = Estimate + `Std. Error`), color = "red", linetype = "dashed")

方法二:绘制水平置信带(与分位数置信带样式一致)

用geom_ribbon绘制覆盖整个x轴的水平置信带,视觉上和分位数的置信带统一:

ggplot(data = d1, aes(
  x = tau, y = Value,
  ymin = Value - Std..Error,
  ymax = Value + Std..Error
)) +
  geom_ribbon(alpha = 0.5) +
  geom_line(color = "blue") +
  labs(x = "Quantiles", y = "xyz") +
  # OLS估计值的红色实线
  geom_hline(data = d2, aes(yintercept = Estimate), color = "red", linewidth = 1) +
  # 覆盖整个x轴的OLS水平置信带
  geom_ribbon(data = d2, aes(
    xmin = min(d1$tau),
    xmax = max(d1$tau),
    ymin = Estimate - `Std. Error`,
    ymax = Estimate + `Std. Error`
  ), alpha = 0.2, fill = "red", inherit.aes = FALSE)
  • inherit.aes = FALSE用于避免继承d1的映射关系,防止x/y变量冲突
  • 可调整alpha和fill参数匹配所需视觉效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:54:58