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

如何用R绘制带单个数据点的平均值堆叠柱状图?

R绘制堆叠均值柱状图并叠加重复样本散点的方法

1. 数据预处理

首先需要把宽格式的原始数据转换为长格式,同时从样本名中提取出条件信息(如A/B),并计算各条件下不同读数类别的平均值:

library(tidyverse)

# 创建示例数据
df = data.frame(sample = c("A1", "A2", "A3", "B1", "B2", "B3"), 
                GFP = c(14, 15, 16, 28, 36, 35), 
                double = c(26, 23, 30, 41, 39, 45), 
                Ab = c(12, 10, 9, 8, 10, 8))

# 转换为长格式并提取条件
df_long <- df %>%
  mutate(condition = str_extract(sample, "^[A-Z]")) %>%
  pivot_longer(cols = c(GFP, double, Ab), names_to = "reading", values_to = "value")

# 计算各条件-读数类别的平均值
df_mean <- df_long %>%
  group_by(condition, reading) %>%
  summarise(mean_value = mean(value), .groups = "drop")

2. 绘制目标图形

使用ggplot2先绘制堆叠的均值柱状图,再叠加每个重复样本的散点。通过position_jitterdodge让散点在对应类别位置轻微偏移,避免重叠:

ggplot() +
  # 堆叠均值柱状图
  geom_col(data = df_mean, 
           aes(x = condition, y = mean_value, fill = reading), 
           position = "stack", alpha = 0.7) +
  # 叠加重复样本散点
  geom_point(data = df_long, 
             aes(x = condition, y = value, color = reading), 
             position = position_jitterdodge(jitter.width = 0.2, dodge.width = 0.7),
             size = 2) +
  # 图形标注与样式调整
  labs(x = "条件", y = "读数", fill = "读数类别", color = "读数类别") +
  theme_bw()

其他数据展示建议

  • 当条件数量较多时,可添加theme(axis.text.x = element_text(angle = 45, hjust = 1))旋转x轴标签,避免重叠。
  • 若想更清晰展示数据分布,可替换堆叠柱状图为分组箱线图+均值点,避免堆叠数值的叠加干扰。
  • 对于多类别读数,使用facet_wrap(~reading)分面展示每个类别,适合条件和读数类别都较多的场景。

内容的提问来源于stack exchange,提问作者M. L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:24:45