如何用ggplot绘制按类型区分颜色的年度收益均值/求和折线图
前置依赖准备
首先加载需要用到的工具包,数据处理用dplyr、绘图用ggplot2,整合在tidyverse套件中:
library(tidyverse)
假设你的原始数据集存为数据框df,字段结构和你给出的样例完全一致,包含Year、Type、Return三列。
版本1:同组取均值绘制折线图
先按「年份+Type」分组计算Return的均值,再生成折线图:
# 数据预处理:分组算均值 df_mean <- df %>% group_by(Year, Type) %>% summarise(Return = mean(Return, na.rm = TRUE), .groups = "drop") # 绘图代码 ggplot(df_mean, aes(x = Year, y = Return, color = Type, group = Type)) + geom_line(linewidth = 1) + geom_point(size = 2) + # 可选,添加数据点方便定位每个年份的取值 labs(x = "年份", y = "平均收益", color = "资产类型") + theme_bw()
说明:na.rm = TRUE会自动过滤Return为空的异常记录,group = Type可以避免因部分年份无对应Type数据导致的折线断裂问题。
版本2:同组取求和值绘制折线图
仅需要把分组汇总的逻辑从mean替换为sum即可:
# 数据预处理:分组算总和 df_sum <- df %>% group_by(Year, Type) %>% summarise(Return = sum(Return, na.rm = TRUE), .groups = "drop") # 绘图代码 ggplot(df_sum, aes(x = Year, y = Return, color = Type, group = Type)) + geom_line(linewidth = 1) + geom_point(size = 2) + labs(x = "年份", y = "总收益", color = "资产类型") + theme_bw()
如果需要补全缺失的年份,可以在预处理步骤添加complete函数填充,默认缺失值可设置为0或者NA:
# 补全年份的可选代码 df_mean_complete <- df_mean %>% complete(Year = full_seq(Year, 1), Type, fill = list(Return = 0))
内容的提问来源于stack exchange,提问作者PCRL
相关产品推荐
相关产品推荐

