我有以下数据框dt(head,6)
:
我需要创建一个图表,其中在x轴上具有年份(2015、2016、2017、2018、2019),各列(W15,W16,W17,W18,W19)各不相同-年)。它们都应按“ TEAM”列分组。
我尝试使用ggplot2
无济于事。
答案 0 :(得分:3)
您需要将数据从宽转换为长,然后使用public function rules()
{
$polymorphExistsRule = '';
if ($this->has('commentable_type')) {
$polymorphExistsRule .= '|model_exists:' . $this->commentable_type . ',id';
}
return [
'commentable_type' => 'required_with:comentable_id,
'comentable_id' => 'required_with:commentable_type' . $polymorphExistsRule,
];
}
。看下面;
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))
答案 1 :(得分:0)
从z
创建一个动物园对象t(dt[-1])
,并从名称的数字部分创建时间)。使用dt $ TEAM作为其列名。最后使用autoplot.zoo
使用ggplot2对其进行绘制。如果您希望每个系列都有一个单独的面板,请删除facet=NULL
。
library(ggplot2)
library(zoo)
z <- zoo(t(dt[-1]), as.numeric(sub("W", "", names(dt)[-1])))
names(z) <- dt$TEAM
autoplot(z, facet = NULL) + scale_x_continuous(breaks = time(z))
假设此输入数据:
set.seed(123)
dt <- data.frame(TEAM = letters[1:5], W15 = rnorm(5), W16 = rnorm(5), W17 = rnorm(5))