【发布时间】: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")
有效,但不是很好,因为日期不对齐:
【问题讨论】: