R语言新手求助:重塑数据以绘制平行坐标图
解决方案
1. 数据重塑
使用tidyverse工具集完成数据格式转换,步骤如下:
步骤1:加载依赖包
library(tidyverse)
步骤2:导入/构造示例数据
如果你的数据已导入R环境,直接使用对应数据集即可:
df <- tibble( ID = c(1, 2, 3), AgeT1 = c(4, 12, 10), AgeT2 = c(7, 13, 12), ScoreT1 = c(15, 5, 6), ScoreT2 = c(22, 10, 6) )
步骤3:转长格式整合数据
将分散的年龄、分数列合并为统一的Age和Score列:
long_df <- df %>% pivot_longer( cols = -ID, names_to = c(".value", "Time"), names_pattern = "(Age|Score)T(\\d)" )
步骤4:转目标宽格式
生成完整年龄范围的列,并填充对应分数:
# 获取数据中覆盖的所有年龄 all_ages <- seq(min(long_df$Age), max(long_df$Age)) wide_df <- long_df %>% pivot_wider( id_cols = ID, names_from = Age, values_from = Score, names_sort = TRUE ) %>% # 补充缺失年龄列,空值设为NA mutate(across(as.character(all_ages), ~replace_na(., NA))) %>% select(ID, as.character(all_ages))
运行后wide_df即为你需要的目标格式。
2. 绘制平行坐标图
推荐使用GGally包快速生成平行坐标图,或用ggplot2手动构建趋势图:
方法1:用GGally生成平行坐标图
library(GGally) ggparcoord( data = long_df, columns = "Age", groupColumn = "ID", valueColumn = "Score", scale = "uniminmax", # 统一轴范围便于对比 showPoints = TRUE, title = "分数随年龄变化平行坐标图" ) + theme_minimal()
方法2:用ggplot2绘制折线趋势图
ggplot(long_df, aes(x = Age, y = Score, color = factor(ID), group = ID)) + geom_line(size = 1) + geom_point(size = 3) + scale_x_continuous(breaks = all_ages) + labs(title = "分数随年龄变化趋势", x = "年龄", y = "分数", color = "ID") + theme_minimal()
内容的提问来源于stack exchange,提问作者user19693102
相关产品推荐
相关产品推荐

