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

如何使用pivot_wider压缩同列值并实现GDP数据聚合与趋势绘图?

GDP时间序列图绘制与数据处理方案

1. 解决散点图混乱问题,绘制清晰的时间序列图

散点图混乱是因为所有国家的GDP数据点重叠在一起了,推荐用两种方式优化:

方案1:展示每个国家的GDP趋势

用折线+颜色区分不同国家,同时降低透明度避免线条重叠:

library(ggplot2)
ggplot(data = country_info_merged_plot,
       aes(x = Year, y = GDP, color = Country)) + 
  geom_line(alpha = 0.7) +
  ggtitle("各国GDP时间序列趋势(2000年起)") +
  theme_minimal() +
  theme(legend.position = "bottom")

方案2:展示年度聚合GDP趋势

先对年度GDP做聚合统计,再绘图(聚合方法见下文)。

2. 用pivot_wider转换为宽格式数据

如果你的数据是长格式(每行对应一个国家-年份的GDP记录),可以用pivot_wider把每个国家转成单独一列,年份作为行索引:

library(tidyr)
wide_gdp_df <- pivot_wider(
  data = country_info_merged_plot,
  id_cols = Year,          # 作为行标识的列(年份)
  names_from = Country,    # 新列名的来源(国家名称)
  values_from = GDP        # 填充新列的数值(GDP数据)
)

转换后的数据更方便对比不同国家同年份的GDP数值。

3. 聚合同一年度的GDP数据

用dplyr按年份分组,统计年度总GDP、平均GDP等聚合值:

library(dplyr)
yearly_agg_gdp <- country_info_merged_plot %>%
  filter(Year >= 2000) %>% # 筛选2000年及以后的数据
  group_by(Year) %>%       # 按年份分组
  summarize(
    total_global_gdp = sum(GDP, na.rm = TRUE), # 年度全球总GDP(忽略缺失值)
    avg_country_gdp = mean(GDP, na.rm = TRUE), # 各国年度平均GDP
    median_country_gdp = median(GDP, na.rm = TRUE) # 各国年度GDP中位数
  )

用聚合后的数据绘制整体趋势图:

ggplot(data = yearly_agg_gdp, aes(x = Year, y = total_global_gdp)) +
  geom_line(color = "#2c3e50", size = 1.2) +
  ggtitle("全球年度总GDP趋势(2000年起)") +
  ylab("总GDP") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:25:11