ggplot2 按年叠加折线图?

ggplot2 overlayed line chart by year?

从以下数据集开始:

  $ Orders,Year,Date
  1608052.2,2019,2019-08-02
  1385858.4,2018,2018-07-27
  1223593.3,2019,2019-07-25
  1200356.5,2018,2018-01-20
  1198226.3,2019,2019-07-15
  837866.1,2019,2019-07-02

尝试制作类似的格式:

使用标准:X 轴将是天或月,Y 轴将是订单总和,分组/颜色将按年份。

尝试次数:

1) 无覆盖

dataset %>%
ggplot( aes(x=`Merge Date`, y=`$ Orders`, group=`Merge Date (Year)`, color=`Merge Date (Year)`)) +
geom_line()

2) ggplot 月份分组

dataset %>%
 mutate(Date = as.Date(`Date`) %>%
 mutate(Year = format(Date,'%Y')) %>%
 mutate(Month = format(Date,'%b')) -> dataset2

 ggplot(data=dataset2, aes(x=Month, y=`$ Orders`, group=Year, color=factor(Year))) + 
 geom_line(size=.75) + 
 ylab("Volume")

lubridate 包就是您的答案。从 Date 字段中提取月份并将其转换为变量。此代码对我有用:

library(tidyverse)
library(lubridate)

dataset <- read_delim("OrderValue,Year,Date\n1608052.2,2019,2019-08-02\n1385858.4,2018,2018-07-27\n1223593.3,2019,2019-07-25\n1200356.5,2018,2018-01-20\n1198226.3,2019,2019-07-15\n837866.1,2019,2019-07-02", delim = ",")
dataset <- dataset %>%
  mutate(theMonth = month(Date))


ggplot(dataset, aes(x = as.factor(theMonth), y = OrderValue, group = as.factor(Year), color = as.factor(Year))) + 
  geom_line()