使用ggplot绘制时间序列,按年份分组的线路

3

我正在尝试绘制一条时间序列,每年都有不同的线。以这个例子为例:

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

这会返回一个警告:geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?。将 color 替换为 group 可以得到类似于我想要的东西,但是由于 x 轴的类型是字符串,所以标签太多了。
你如何使 x 轴仅显示每个月的第一天?或者有没有更好的方法来绘制这样的时间序列图? TimeSeriesPlot

如果我移除 x=format(dt,format="%m-%d") 并且改用 x=dt,我得到了正确的格式。更多选项请参见 http://ggplot2.tidyverse.org/reference/scale_date.html。 - Jason
1个回答

2

我认为最简单的方法是将所有日期转换为同一年份,并将其用于绘制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")

这将返回

在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接