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

Base R中Dynamite Plot设置双向不对称误差棒的实现方法

解决方案:实现不对称误差棒的Dynamite Plot

要实现不对称的误差棒,你需要修改原函数的参数逻辑,让它分别接收下误差和上误差的数值,而非单一的对称误差值。以下是具体修改步骤和完整代码:

1. 修改Dynamite Plot函数

将原函数的error参数拆分为lower_error(向下延伸的误差)和upper_error(向上延伸的误差),同时调整误差棒绘制和边界计算逻辑:

dynamitePlot <- function(height, lower_error, upper_error, names = NA, significance = NA, ylim = NULL, ...){
  # 自动计算y轴范围:下限取0或height-lower_error的最小值(避免误差棒超出y轴0值以下),上限取1.1倍的height+upper_error最大值
  if(is.null(ylim)){
    minLim <- max(0, min(height - lower_error))
    maxLim <- 1.1 * max(height + upper_error)
    ylim <- c(minLim, maxLim)
  }
  bp <- barplot(height, names.arg = names, ylim = ylim, ...)
  # 绘制向下的误差棒
  arrows(x0 = bp, y0 = height, y1 = height - lower_error, angle = 90, code = 2)
  # 绘制向上的误差棒
  arrows(x0 = bp, y0 = height, y1 = height + upper_error, angle = 90, code = 2)
  # 调整显著性文本位置,基于上误差顶端
  text(x = bp, y = 2 + height + upper_error, labels = significance, cex=1.5)
}

2. 定义不对称误差数据

根据你的需求,分别定义每个处理组的上下误差:

  • T2:下误差13,上误差8
  • T1:下误差3,上误差13
  • C:下误差6,上误差12
# 试验数据
x <- c("T2", "T1", "C")
df <- data.frame("cats" = x)

# 绘图数值
Values <- c(72,60,20) # y轴百分比数值
Lower_Errors <- c(13, 3, 6)  # 向下延伸的误差
Upper_Errors <- c(8, 13, 12) # 向上延伸的误差
Sig <- c("A","A","B") # 统计显著性标记

3. 绘制带不对称误差棒的图

调用修改后的函数,传入上下误差参数:

par(mar=c(5,5,2,1))
pallet <- c('#111111','#222222','#333333') 

# 生成图形
dynamitePlot(Values, 
             lower_error = Lower_Errors, 
             upper_error = Upper_Errors, 
             significance = Sig, 
             names = df$cats,
             col=pallet, 
             width=rep(0.6, 3), # 调整柱子宽度为合理值(原0.03过窄)
             ylim = c(0,100), 
             cex.axis=1.5, 
             cex.lab=1.5,
             ylab="Percent [%]", 
             xlab="Treatment")

关键修改说明

  • 新增lower_error和upper_error参数,分别控制误差棒的上下延伸长度
  • 自动计算y轴范围时,避免误差棒超出y轴0值下限
  • 用code=2参数确保误差棒箭头仅在末端显示,符合常规样式
  • 调整柱子宽度为合理值,解决原代码柱子几乎不可见的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:38:18