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

如何使用R base复现该含误差棒与标注的分组条形图?

用R基础绘图复现ggplot2分组柱状图效果

我已经用ggplot2实现了包含分组柱状图、误差棒、显著性标记的目标图表,现在需要用R基础绘图系统复现相同效果。

原始ggplot2代码

ggplot(data_summary, aes(x = factor(Temp), y = mean, fill = Glass)) + 
  geom_bar(stat = "identity", position = "dodge", alpha = 0.5, colour = "gray25")  +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.25,
                show.legend = FALSE, colour = "gray25") +
  labs(x="Temperature (˚C)", y="Light Output") +
  theme_bw() + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
  theme(legend.position = c(0.1, 0.75)) +
  geom_text(aes(label=Tukey), position = position_dodge(0.90), size = 3, 
            vjust=-0.8, hjust=-0.5, colour = "gray25") +
  ylim(0, 1500) +
  scale_fill_grey()

R基础绘图实现代码

R基础绘图需要手动处理分组位置、误差棒和文本标注,以下是完整复现代码:

# 1. 数据预处理:排序并计算柱子位置
data_summary <- data_summary[order(data_summary$Temp, data_summary$Glass), ]
temp_levels <- unique(data_summary$Temp)
n_temp <- length(temp_levels)
n_glass <- length(unique(data_summary$Glass))
bar_width <- 0.35
dodge_width <- bar_width * 0.9
data_summary$x_pos <- rep(1:n_temp, each = n_glass) + rep(c(-dodge_width/2, dodge_width/2), n_temp)

# 2. 初始化画布,匹配theme_bw样式
par(mar = c(4, 4, 2, 2), bg = "white", bty = "l")
plot(0, 0, type = "n", 
     xlim = c(0.5, n_temp + 0.5), ylim = c(0, 1500),
     xlab = "Temperature (˚C)", ylab = "Light Output",
     xaxt = "n")
axis(1, at = 1:n_temp, labels = temp_levels)

# 3. 绘制分组柱状图(灰色半透明填充+边框)
fill_cols <- adjustcolor(c("gray60", "gray80"), alpha.f = 0.5)
for (i in seq_len(nrow(data_summary))) {
  rect(data_summary$x_pos[i] - bar_width/2, 0,
       data_summary$x_pos[i] + bar_width/2, data_summary$mean[i],
       col = fill_cols[match(data_summary$Glass[i], unique(data_summary$Glass))],
       border = "gray25")
}

# 4. 添加误差棒
for (i in seq_len(nrow(data_summary))) {
  y_low <- data_summary$mean[i] - data_summary$sd[i]
  y_high <- data_summary$mean[i] + data_summary$sd[i]
  lines(rep(data_summary$x_pos[i], 2), c(y_low, y_high), col = "gray25")
  segments(data_summary$x_pos[i] - 0.125, y_low,
           data_summary$x_pos[i] + 0.125, y_low, col = "gray25")
  segments(data_summary$x_pos[i] - 0.125, y_high,
           data_summary$x_pos[i] + 0.125, y_high, col = "gray25")
}

# 5. 添加Tukey显著性标记
for (i in seq_len(nrow(data_summary))) {
  text(x = data_summary$x_pos[i], 
       y = data_summary$mean[i] + data_summary$sd[i] + 30,
       labels = data_summary$Tukey[i], 
       col = "gray25", cex = 0.8, adj = c(-0.5, 0))
}

# 6. 添加图例(对应原图表的位置)
legend("topleft", inset = c(0.05, 0.05),
       legend = unique(data_summary$Glass),
       fill = fill_cols, border = "gray25",
       bty = "n", cex = 0.8)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:25:32