如何让R ggplot折线图跳过缺失数据点,解决手动色阶值不足报错
问题原因
- 报错
"Error: Insufficient values in manual scale. 4 needed but only 3 provided."是因为scale_color_manual中仅配置了3种颜色,而你的athlete字段共有4个不同取值(包含缺席的受试者),颜色数量和分组数量不匹配。 - 要保留缺席受试者的折线,需要先补全数据集内所有受试者和所有测试周的组合,缺失的测试数据填充为NA即可,ggplot会自动跳过NA值但保留对应分组的折线。
操作步骤
- 先补全数据集:
library(tidyr) # 生成所有受试者和测试周的全组合,缺失的峰值速度填充为NA Jump_tibble_completed <- Jump_tibble %>% complete(athlete, game)
- 修改绘图代码,补全第四种颜色、替换为补全后的数据集:
Jump_vel_tracking <- ggplot(Jump_tibble_completed, aes(x = game, y = daily_max_vel, color = athlete)) + # 新增第四种颜色对应第四名受试者,可根据需求调整颜色值 scale_color_manual(values = c("red" , "blue", "purple", "green")) + geom_point(na.rm = TRUE) + geom_line(aes(group = athlete), na.rm = TRUE) + scale_y_continuous(breaks = seq(from = 3.0, to = 3.8, by = 0.1), limits = c(3.0, 3.8)) + labs(x = 'Game', y = 'Peak Velocity (m/s)', title = "Season CMJ Peak Velocity") + theme(panel.background = element_rect (fill = 'gray88', colour = 'orange')) + theme(plot.background = element_rect (fill = 'orange', color = 'orange')) + theme(panel.grid = element_blank()) + theme(legend.position = 'none', legend.title = element_blank(), legend.background = element_rect(fill = 'orange'), legend.key = element_rect(fill = 'orange')) + theme(axis.text.x = element_text(size = 10, angle = 0)) + theme(axis.title.x=element_blank()) Jump_vel_tracking
内容的提问来源于stack exchange,提问作者Ben McCarthy
相关产品推荐
相关产品推荐

