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

基于不同年份DataFrame绘制多列均值的ggplot2实现

解决R语言ggplot2绘制年份-均值散点图问题

问题背景

现有三个对应1930、1990、2020年的R语言DataFrame:

df_1 <- data.frame(total = c(0.9, 0.4, 0.2), white = c(0.6, 0.2, 0.1), black = c(0.3, 0.2, 0.1), immigrant = c(0.7, 0.3, 0.9))

df_2 <- data.frame(total = c(0.8, 0.7, 0.6), white = c(0.4, 0.3, 0.2), black = c(0.4, 0.4, 0.4), immigrant = c(0.9, 0.2, 0.1))

df_3 <- data.frame(total = c(0.6, 0.8, 0.9), white = c(0.4, 0.2, 0.7), black = c(0.2, 0.6, 0.2), immigrant = c(0.6, 0.8, 0.5))

需求

使用ggplot2工具完成以下操作:

  • 计算每个DataFrame中四列(total、white、black、immigrant)的均值
  • 绘制散点图:x轴为年份(1930、1990、2020),y轴为0-1区间的计算均值,各人口统计组以散点形式区分展示

尝试的错误代码

list(df_1, 
     df_2,
     df_3) %>%
     lapply(function(x) setNames(x, 'ratio')) %>%
     {do.call(bind_rows, c(., .id = 'demographic'))} %>%
     mutate(ratio = mean(ratio)) %>%
     group_by(demographic) %>%
     ggplot(aes(ratio, n, colour = demographic, group = demographic)) +
     labs(x="Mean", y="Year", ))

正确实现方案

核心思路是先给每个DataFrame绑定对应年份,再将宽格式数据转为长格式,最后按年份和人口组计算均值并绘图。

完整代码:

library(tidyverse)
library(ggplot2)

# 给每个数据框绑定年份并合并
combined_df <- bind_rows(
  df_1 %>% mutate(year = 1930),
  df_2 %>% mutate(year = 1990),
  df_3 %>% mutate(year = 2020)
)

# 转长格式并计算各年份-人口组的均值
summary_df <- combined_df %>%
  pivot_longer(cols = -year, names_to = "demographic", values_to = "ratio") %>%
  group_by(year, demographic) %>%
  summarize(mean_ratio = mean(ratio), .groups = "drop")

# 绘制散点图
ggplot(summary_df, aes(x = factor(year), y = mean_ratio, color = demographic)) +
  geom_point(size = 3) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(
    x = "年份",
    y = "均值",
    color = "人口统计组",
    title = "各年份不同人口组均值变化"
  ) +
  theme_minimal()

关键步骤解释

  1. 绑定年份:通过mutate给每个数据框添加对应年份列,用bind_rows合并,解决年份与数据框的对应问题,兼容不同行数的输入。
  2. 转长格式:pivot_longer将宽格式(每列对应一个人口组)转为长格式,统一数据结构,方便后续分组计算。
  3. 计算均值:按year和demographic分组,用summarize计算每组均值,.groups = "drop"避免分组残留影响绘图。
  4. 绘图设置:x轴用factor(year)确保年份按指定顺序显示,scale_y_continuous固定y轴范围在0-1区间,散点按人口组区分颜色,清晰展示各组均值随年份的变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:05:23