首页 > 解决方案 > 在不同的列中绘制具有年份的时间序列

问题描述

我有以下数据框dt(head,6)

dt(头,6)

我需要创建一个图表,其中 x 轴上有年份(2015、2016、2017、2018、2019),不同的列(W15、W16、W17、W18、W19 - 每一个都与一年有关) y 轴。它们都应按 TEAM 列分组。

我尝试使用ggplot2无济于事。

标签: rggplot2plottime-series

解决方案


您需要将数据从宽转换为长,然后使用ggplot. 往下看;

library(tidyverse)

dt %>% 
  pivot_longer(., -Team, values_to = "W", names_to = "Year") %>% 
  mutate(Year = as.integer(gsub("W", "20", Year))) %>% 
  ggplot(., aes(x=Year, y=W, group=Team)) +
  geom_line(aes(color=Team))

数据:

dt <- structure(list(Team = c("AC", "AF", "AK", "AL", "AA&M", "Alst", "Alb"), 
                     W15 = c(7L, 12L, 20L, 18L, 8L, 17L, 24L), 
                     W16 = c(9L, 12L, 25L, 18L, 10L, 12L, 23L), 
                     W17 = c(13L, 12L, 27L, 19L, 2L, 8L, 21L), 
                     W18 = c(16L, 12L, 14L, 20L, 3L, 8L, 22L), 
                     W19 = c(27L, 14L, 17L, 18L, 5L, 12L, 12L)), 
                class = "data.frame", row.names = c(NA, -7L))
#   Team W15 W16 W17 W18 W19
# 1   AC   7   9  13  16  27
# 2   AF  12  12  12  12  14
# 3   AK  20  25  27  14  17
# 4   AL  18  18  19  20  18
# 5 AA&M   8  10   2   3   5
# 6 Alst  17  12   8   8  12
# 7  Alb  24  23  21  22  12

推荐阅读