【问题标题】:Plotting multiple years with ggplot across Jan1 r在 Jan1 r 中使用 ggplot 绘制多年
【发布时间】:2025-12-09 13:15:02
【问题描述】:

我正在尝试在 r 中的 ggplot 上绘制跨越 1 月 1 日的几年数据,并希望将系列排列起来。如果感兴趣的时期没有超过 1 月 1 日,我可以创建变量来绘制所有年份都设置为相同值的地方,使用类似的东西:

library(lubridate)
library(ggplot2)
library(dplyr)

Dates = ymd(c("2018-08-01", "2018-09-15", "2018-11-20", "2019-01-15", "2019-03-15", "2019-08-15", "2019-09-20", "2019-12-02", "2020-01-15", "2020-03-20" ))
Values = rep(c(15, 14, 10, 8, 4), times = 2)
Period = rep(c("Before", "After"), each = 5)

my_df = data.frame(Dates, Values, Period)

my_df = my_df %>%
      mutate(plot.date = `year<-`(Dates, 2020))

my_df %>%
      ggplot(aes(x = plot.date, y = Values, color = Period))+
      geom_line()
      

但这会在错误的位置中断系列。

我正在寻找更像这样的东西,我通过手动更改第二组中的年份以匹配第一组来实现。

我也尝试使用原始日期和方面,但这不是很好,因为该系列的开始日期和结束日期不同(8 月 1 日和 3 月 1 日与 8 月 23 日和 3 月 23 日),所以使用 scales = " free_x" 他们没有排队。

my_df %>%
      ggplot(aes(x = Dates, y = Values))+
      geom_line()+
      facet_wrap( ~ Period, ncol = 1, scales = "free_x")

有效,但不是很好,因为日期不对齐:

【问题讨论】:

    标签: r date ggplot2


    【解决方案1】:

    不完全确定您想要使用 scales = "free_x" 做什么,但实现第二张图表的另一种方法是计算到 1 月 1 日的天数并使用一些标记标签绘制数据。

    library(lubridate)
    library(ggplot2)
    library(dplyr)
    
    graph_data <- my_df %>%
      group_by(Period) %>%
      mutate(jan_first = as.Date(paste0(year(max(Dates)), "-01-01"))) %>%
      mutate(days_diff_jan_first = as.numeric(difftime(Dates, jan_first, units = "days")))
    
    
    breaks <- as.numeric(difftime(seq(as.Date("2018-06-01"), as.Date("2019-05-01"),
      by = "1 month"),
      as.Date("2019-01-01"), units = "days"))
    labels <- c("Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar",
      "Apr", "May")
    
    
    ggplot(data = graph_data) +
      geom_line(mapping = aes(x = days_diff_jan_first, y = Values, color = Period)) +
      scale_x_continuous(breaks = breaks, labels = labels) +
      xlab("Month")
    

    reprex package 创建于 2021-04-30 (v2.0.0)

    【讨论】: