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

如何用ggplot绘制含班级均值与总体均值的分组柱状图

问题背景

给定如下数据集:

example <- data.frame (
  code = c("850304", "850302", "850305", "404013", "404001", "404016"), 
  class = c("8503", "8503", "8503", "4040", "4040", "4040"), 
  partizipation_t1 = c(3.5, 2.0, 1.6, 3.0, 1.2, 3.9), 
  partizipation_t2 = c(3.7, 2.3, 2.0, 3.2, 1.5, 3.7)
)

其中partizipation_t1、partizipation_t2分别代表两次测量的参与度数值。需要制作分组柱状图:x轴为测量时间点(T1/T2),y轴为参与度均值,每个时间点需同时展示指定班级均值和总体均值两类柱子。

解决方案

步骤1:将数据集转换为长格式

先把宽格式的时间列转为长格式,方便后续统一计算均值:

library(tidyverse)

# 转换整个数据集为长格式
example_long <- example %>%
  rename(T1 = partizipation_t1, T2 = partizipation_t2) %>%
  pivot_longer(cols = c(T1, T2), names_to = "Time", values_to = "Partizipation")

步骤2:分别计算班级均值与总体均值

指定目标班级(示例为8503),分别计算该班级和全体数据的时间点均值,再合并为带分组标识的数据集:

# 计算目标班级的均值
class_means <- example_long %>%
  filter(class == "8503") %>%
  group_by(Time) %>%
  summarise(Mean = mean(Partizipation, na.rm = TRUE)) %>%
  mutate(Group = "班级均值")

# 计算总体均值
overall_means <- example_long %>%
  group_by(Time) %>%
  summarise(Mean = mean(Partizipation, na.rm = TRUE)) %>%
  mutate(Group = "总体均值")

# 合并两个结果集
combined_means <- bind_rows(class_means, overall_means)

步骤3:绘制分组柱状图

利用ggplot的分组功能,让两类均值的柱子在同一时间点并排展示:

ggplot(combined_means, aes(x = Time, y = Mean, fill = Group)) +
  geom_bar(stat = "identity", width = 0.6, position = position_dodge(width = 0.7)) +
  scale_fill_manual(values = c("steelblue", "orange")) +
  labs(
    y = "参与度均值",
    x = "测量时间点",
    title = "班级与总体参与度均值对比",
    fill = "均值类型"
  ) +
  theme_classic() +
  coord_cartesian(ylim = c(1, 4))

效果说明

  • 每个时间点会显示两个并排柱子,清晰区分目标班级和全体数据的均值
  • 图例直观展示两类均值的对应颜色
  • 可通过调整width和position_dodge参数,自定义柱子宽度与间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:15:56