r - 在不同的列中绘制具有年份的时间序列
问题描述
我有以下数据框dt(head,6)
:
我需要创建一个图表,其中 x 轴上有年份(2015、2016、2017、2018、2019),不同的列(W15、W16、W17、W18、W19 - 每一个都与一年有关) y 轴。它们都应按 TEAM 列分组。
我尝试使用ggplot2
无济于事。
解决方案
您需要将数据从宽转换为长,然后使用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
推荐阅读
- c - 计算和打印矩阵的对角线之和
- javascript - 如何在 Angular 中使用 addEventListener 和 postMessage?
- php - 如何将日期、时间和值从单选按钮放入数据库
- c# - 逐个像素地动态绘制和显示,有一些延迟
- npm - 如何从 Nexus oss 代理获取依赖于 github 项目的 npm 包
- django - Django 测试 - 发送包含整数的数组数组
- android - 在 android 中使用改造登录
- json - 我如何在 nunjuncks 中乘以数据?
- swift - 为什么不能在swift中将可变参数标记为inout?
- vue.js - Vue Js 2 / Vue-CLI 3 / 托管时显示空白页