本文介绍了在不同的列中用年绘制时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框 dt(head,6)
:
我需要创建一个图表,其中在x轴上具有年份(2015、2016、2017、2018、2019),各列(W15,W16,W17,W18,W19)各不相同-年).它们都应按"TEAM"列分组.
I need to create a graph in which I have the years (2015, 2016, 2017, 2018, 2019) on the x-axis , different columns (W15, W16, W17, W18, W19 - each one relates to one year) on the y-axis. They are all should be grouped by the column TEAM.
我尝试使用 ggplot2
无济于事.
推荐答案
您需要将数据从宽转换为长,然后使用 ggplot
.看下面;
You need to convert your data from wide to long and then use ggplot
. Look below;
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))
数据:
Data:
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
这篇关于在不同的列中用年绘制时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!