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

在Plotly R中基于数据绘制置信区间:误差线不显示问题

解决Plotly R柱状图误差线不显示的问题

你的代码误差线不显示的核心原因是:error_y里的y_min和y_max设置的绝对数值远小于柱子的y值,比如1993年柱子高度是123.2,但你把误差下限设为32.1、上限设为45.3,误差线被压缩到柱子底部,肉眼完全无法识别。

根据你的lower_int和upper_int的含义,分两种情况解决:

情况1:lower_int/upper_int是相对于柱子高度的偏差幅度

如果这两个值是「柱子下方需要向下延伸的误差长度」和「柱子上方需要向上延伸的误差长度」,直接用array和arrayminus参数:

library(plotly)

year <- c("1993","1994","1995","1996")
incident <- c(123.2,489.2,281.3,892.1)
lower_int <- c(32.1,23.1,11.1,34.2)
upper_int <- c(45.3,43.5,25.6,59.0)
data <- data.frame(year, incident, lower_int, upper_int)

fig <- plot_ly(data, x = ~year, y = ~incident, type = 'bar',
        error_y = ~list(
          array = ~upper_int,       # 柱子向上延伸的误差幅度
          arrayminus = ~lower_int,  # 柱子向下延伸的误差幅度
          visible = TRUE            # 强制确保误差线可见
        ))

fig

情况2:lower_int/upper_int是误差线的绝对上下限

如果这两个值是误差线的最低/最高绝对坐标,那需要先调整数值,确保它们围绕柱子的y值(比如你可能误把偏差幅度写成了绝对数值),计算正确的上下限后再传入y_min和y_max:

library(plotly)

year <- c("1993","1994","1995","1996")
incident <- c(123.2,489.2,281.3,892.1)
lower_error <- c(32.1,23.1,11.1,34.2)
upper_error <- c(45.3,43.5,25.6,59.0)

# 计算误差线的绝对上下限:柱子高度 ± 偏差幅度
data <- data.frame(
  year = year,
  incident = incident,
  y_min = incident - lower_error,
  y_max = incident + upper_error
)

fig <- plot_ly(data, x = ~year, y = ~incident, type = 'bar',
        error_y = ~list(
          y_min = ~y_min,
          y_max = ~y_max,
          visible = TRUE
        ))

fig

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:55:20