【问题标题】:ggplot2 overlayed line chart by year?ggplot2按年叠加折线图?
【发布时间】:2019-08-27 18:58:09
【问题描述】:

从以下数据集开始:

  $ 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")

【问题讨论】:

    标签: r ggplot2 timeserieschart


    【解决方案1】:

    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()
    

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 2021-11-21
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多