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

ggplot2绘制棒球选手多指标折线图:无数据/连线异常问题

解决ggplot2绘制多组折线图连线混乱问题

问题场景

要绘制2017-2022年棒球选手Ian Happ的BA(打击率)、OBP(上垒率)、SLG(长打率)、OPS(上垒加长打率)多线折线图,初始宽表代码无数据显示,转长表后仅能显示散点,折线无法正确连接,添加group=1后连线混乱。

问题原因

转长表后,ggplot未按统计类型(type字段)对数据分组,导致折线无法识别不同类别;而group=1会将所有数据归为同一组,造成交叉连线。

解决方案

将group与color同时绑定到type字段,让ggplot自动按统计类型分组绘制折线;同时确保Year为数值型(若原数据是字符型需转换)。

修正后的完整代码

library(tidyverse)

# 读取数据并预处理
happData <- read_csv("my pathfile")

slashline <- happData %>% 
  select(Year, BA, OBP, SLG, OPS) %>% 
  slice(-c(7, 8))  # 替代索引删除行,更符合tidyverse风格

# 宽表转长表(用pivot_longer替代已退役的gather)
slashline2 <- slashline %>% 
  pivot_longer(cols = c(BA, OBP, SLG, OPS), 
               names_to = "type", 
               values_to = "value")

# 绘制折线图
ggplot(slashline2, aes(x = Year, y = value, color = type, group = type)) +
  geom_point(size = 2) +  # 增大散点提升辨识度
  geom_line(alpha = 0.7, linewidth = 1) +  # 调整线宽与透明度
  labs(y = "数值",
       title = "Ian Happ's Statistics, 2017-2022") +
  theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
        legend.position = "bottom") +
  guides(color = guide_legend(title = "统计类型")) +
  scale_color_discrete(labels = c("Batting Average", "On-Base Percentage", 
                                 "Slugging Percentage", "On-Base Plus Slugging")) +
  scale_x_continuous(breaks = 2017:2022)  # 强制显示每年刻度

关键说明

  • 替换gather为pivot_longer:gather已被tidyverse标记为退役函数,pivot_longer功能更灵活,是当前推荐用法。
  • group = type:核心修正点,确保ggplot按每个统计类型单独连线,避免跨类别混乱。
  • 细节优化:调整散点大小、线宽、标题样式,添加X轴固定刻度,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:22:19