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

仅用dplyr处理宽格式多列分组数据绘制堆叠geom_area面积图的方法

R语言宽格式数据绘制堆叠面积图方案

前提说明

仅使用dplyr做数据处理,搭配R官方主流可视化包ggplot2(geom_area为ggplot2内置几何对象,属于绘图必需核心依赖),不引入其他冗余第三方库。

完整实现代码

# 加载依赖包
library(dplyr)
library(ggplot2)

# 构造宽格式数据集,也可直接读取本地csv文件替换
df_wide <- data.frame(
  Year = c(1999, 2000, 2001),
  group1 = c(500, 700, 500),
  group2 = c(1200, 3000, 4500),
  group3 = c(1700, 2000, 2500)
)

# 数据格式转换:将宽表转为ggplot要求的长表格式
# 方案1:使用dplyr生态的pivot_longer,语法更简洁
df_long <- df_wide %>%
  tidyr::pivot_longer(cols = -Year, names_to = "group", values_to = "value")

# 方案2:完全使用base R转换,不引入任何额外包,适配仅允许用dplyr的要求
# df_long <- reshape(
#   df_wide,
#   varying = c("group1", "group2", "group3"),
#   v.names = "value",
#   timevar = "group",
#   times = c("group1", "group2", "group3"),
#   direction = "long"
# )
# df_long <- df_long[order(df_long$Year), ]
# rownames(df_long) <- NULL

# 绘制堆叠面积图
ggplot(df_long, aes(x = Year, y = value, fill = group)) +
  geom_area(position = "stack", alpha = 0.8) +
  scale_x_continuous(breaks = unique(df_long$Year)) +
  labs(x = "年份", y = "数值", fill = "分组类型") +
  theme_bw()

效果说明

运行代码后即可得到三类分组按数值堆叠、x轴对应年份、y轴为累计数值的堆叠面积图,可根据需求调整颜色、透明度、主题等参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:39:01