如何在R中绘制含X1~X7多指标的年度趋势折线图
R多指标时间折线图实现方案
ggplot2 实现
你当前代码的核心问题是未将宽格式的原始数据转为ggplot所需的长(tidy)格式,且未正确配置分组映射,完整可运行代码如下:
# 加载依赖包 library(tidyverse) library(viridis) library(plotly) # 若使用theme_ipsum需要额外加载hrbrthemes包,未安装可先运行install.packages("hrbrthemes") # library(hrbrthemes) # 构造测试数据,如果你已有数据可跳过这一步直接读取 data <- data.frame( Year = c(2004, 2005, 2006, 2007, 2008), X1 = c(0.91, 0.57, 1.30, 0.44, 1.69), X2 = c(0.23, -0.03, -0.43, 0.63, 0.34), X3 = c(0.28, 0.88, 1.95, 0.60, -2.81), X4 = c(1.02, 0.52, 1.27, 0.34, -2.41), X5 = c(0.90, 0.47, 1.00, 0.60, -1.80), X6 = c(0.95, 0.55, 1.19, 0.50, -1.87), X7 = c(0.94, 0.56, 1.26, 0.46, -1.83) ) # 宽数据转长格式 data_long <- data %>% pivot_longer(cols = -Year, names_to = "indicator", values_to = "value") # 绘制折线图 p <- data_long %>% ggplot(aes(x = Year, y = value, color = indicator, group = indicator)) + geom_line(linewidth = 1) + scale_color_viridis(discrete = TRUE) + ggtitle("multiple X over time") + xlab("年份") + ylab("指标值") + # 不需要图例可打开下一行注释 # theme(legend.position = "none") + theme_minimal() # 要使用theme_ipsum替换上面的theme_minimal即可 # theme_ipsum() # 静态图输出 print(p) # 交互式图输出 ggplotly(p)
基础R实现
基础R中可以用matplot快速实现多折线图,无需数据格式转换,代码更简洁:
# 提取x轴年份和y轴指标矩阵 year_vec <- data$Year val_matrix <- as.matrix(data[, -1]) # 绘制多折线图 matplot( x = year_vec, y = val_matrix, type = "l", lty = 1, lwd = 2, col = viridis::viridis(7), # 也可直接写col = 1:7使用默认颜色 main = "multiple X over time", xlab = "年份", ylab = "指标值" ) # 添加图例 legend( "topright", legend = colnames(val_matrix), col = viridis::viridis(7), lty = 1, lwd = 2, cex = 0.8 )
内容的提问来源于stack exchange,提问作者dbraeuni
相关产品推荐
相关产品推荐

