如何在 R 中的同一张图中将不同的月份绘制为不同的系列
How to plot different months as different series in the same graph in R
我有以下数据集
head(Data)
Fecha PriceStats
1 01-2002 45.2071
2 02-2002 46.6268
3 03-2002 48.4712
4 04-2002 53.5067
5 05-2002 55.6527
6 06-2002 57.6684
共有 176 个观测值。
每一行对应不同的月份。
我想创建一个图表,其中 x 轴为一年中的 12 个月,数据集的每一年(每年包含 12 个月)对应于图表中的一个系列,因此我可以绘制所有不同的年份重叠(在这种情况下将是 15 个系列)。
我是否必须在数据集上设置级别或 ggplot 可以直接执行此操作?
应该这样做:
library(ggplot2)
library(lubridate)
Data <- data.frame(date = seq(ymd('2014/01/01'), ymd('2016/12/01'), 30),
n = sample(1:50, 36))
Data$month <- month(Data$date)
Data$year <- year(Data$date)
ggplot(Data, aes(x = month, y = n, group = year)) +
geom_line(aes(colour = as.factor(year)))
我有以下数据集
head(Data)
Fecha PriceStats
1 01-2002 45.2071
2 02-2002 46.6268
3 03-2002 48.4712
4 04-2002 53.5067
5 05-2002 55.6527
6 06-2002 57.6684
共有 176 个观测值。
每一行对应不同的月份。
我想创建一个图表,其中 x 轴为一年中的 12 个月,数据集的每一年(每年包含 12 个月)对应于图表中的一个系列,因此我可以绘制所有不同的年份重叠(在这种情况下将是 15 个系列)。
我是否必须在数据集上设置级别或 ggplot 可以直接执行此操作?
应该这样做:
library(ggplot2)
library(lubridate)
Data <- data.frame(date = seq(ymd('2014/01/01'), ymd('2016/12/01'), 30),
n = sample(1:50, 36))
Data$month <- month(Data$date)
Data$year <- year(Data$date)
ggplot(Data, aes(x = month, y = n, group = year)) +
geom_line(aes(colour = as.factor(year)))