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

如何在ggplot折线图中添加分组均值水平线段?

复刻Prism样式的配对处理折线图解决方案

1. 修正均值数据计算

之前仅按Treatment分组计算均值,无法对应x轴的Trt_Seq类别,需同时按Treatment和Trt_Seq分组,得到每个处理序列在对应处理下的均值:

# 计算每个Treatment-Trt_Seq组合的O2均值
mean_O2 <- aggregate(O2 ~ Treatment + Trt_Seq, data = sample_data, FUN = mean)

2. 修正绘图代码(复刻Prism风格)

调整geom_segment的坐标逻辑,让均值线对应正确的x轴位置,同时更换主题、优化样式:

library(ggplot2)

# 色盲友好配色(仅取AB/BA对应的两个颜色)
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

ggplot(sample_data, aes(x = factor(Trt_Seq), y = O2, group = Record_ID, color = Treatment)) +
  # 绘制个体配对连线(降低透明度避免遮挡)
  geom_line(alpha = 0.6) +
  # 绘制个体数据点
  geom_point(size = 2) +
  # 绘制均值短横线:在对应x位置左右偏移,避免不同Treatment的均值线重叠
  geom_segment(data = mean_O2, 
               aes(x = as.numeric(factor(Trt_Seq)) - 0.15, 
                   xend = as.numeric(factor(Trt_Seq)) + 0.15, 
                   y = O2, yend = O2),
               size = 1.2, show.legend = FALSE) +
  # 可选:添加均值点标记(菱形增强辨识度)
  geom_point(data = mean_O2, aes(y = O2), size = 3, shape = 18, show.legend = FALSE) +
  # 设置配色
  scale_colour_manual(values = cbPalette[c(2, 6)]) +
  # 切换为Prism风格的经典主题(无网格线)
  theme_classic(base_size = 16) +
  # 优化主题细节:加粗标题、坐标轴,居中图表标题
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.title.x = element_text(face = "bold"),
    axis.title.y = element_text(face = "bold"),
    axis.text = element_text(color = "black"),
    axis.line = element_line(size = 0.8),
    legend.title = element_text(face = "bold")
  ) +
  # 坐标轴范围与标签
  ylim(0, 45) +
  ylab("Peak O2") +
  xlab("Treatment") + 
  ggtitle("Peak O2 Treatment Effect")

关键修正说明

  • 均值数据修正:通过Treatment + Trt_Seq分组,确保每个均值都对应到x轴的正确处理位置(A/B),解决了之前坐标错位导致的异常线条。
  • 均值线位置调整:用as.numeric(factor(Trt_Seq)) ± 0.15让同一x位置上的不同Treatment均值线左右分开,避免重叠。
  • Prism风格适配:使用theme_classic替代theme_bw,移除网格线,同时加粗标题、坐标轴线条,贴近Prism软件的默认图表风格。

如果需要添加误差线(如标准误),可以扩展均值计算:

# 计算均值+标准误
mean_se_O2 <- aggregate(O2 ~ Treatment + Trt_Seq, data = sample_data, 
                        FUN = function(x) c(mean = mean(x), se = sd(x)/sqrt(length(x))))
mean_se_O2 <- do.call(data.frame, mean_se_O2)

# 在绘图中添加误差线
geom_errorbar(data = mean_se_O2, 
              aes(x = factor(Trt_Seq), ymin = O2.mean - O2.se, ymax = O2.mean + O2.se),
              width = 0.1, show.legend = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:42:12