在 ggplot 中绘制时间序列,线条按年份分组

Plotting a Time Series in ggplot, with lines grouped by Year

我正在尝试绘制一个时间序列,每个年份都在不同的线上。举个例子:

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

df = data.frame(dt = seq(as.Date("2015/01/01"), by = "day", length.out = 1000),
     num = c(sample(1:333), sample(333:665), sample(665:998)))

使用此示例数据,我尝试绘制:

ggplot(df, aes(x= format(dt, format="%m-%d"), y=num, group = as.factor(year(dt)))) 
    + geom_line()

这个returns一个警告那个geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?。将 color 替换为 group 得到了与我想要的类似的东西,但是 x 轴的标签太多,因为它的类型是字符串。

如何让 x 轴在这里只显示每个月的第一天?或者有没有更好的方法来绘制这样的时间序列?

我认为最简单的方法是将所有日期转换为同一年并将其用于绘制 x 轴。然后您可以自定义比例以获得您想要的标签。例如

same_year <- function(x) {
  year(x) <- 2000
  x
}

ggplot(df, aes(x=same_year(dt), y=num, color = as.factor(year(dt)))) + 
  geom_line()  + 
  scale_x_date(date_breaks = "1 month", date_labels="%b")

哪个returns