有效地使用 lubridate 和 ggplot2 作为日期轴

Using lubridate and ggplot2 effectively for date axis

考虑这个例子:

library(ggplot2)
library(lubridate)

set.seed(4)
date   <- seq(from = as.POSIXct("2012-01-01"), to = as.POSIXct("2014-12-31"), by = "days")
value  <- c(rnorm(274, 50, 1), rnorm(274, 55, 1), rnorm(274, 55, 2), rnorm(274, 60, 2))
df     <- data.frame(date, value)

head(df)
#         date    value
# 1 2012-01-01 50.21675
# 2 2012-01-02 49.45751
# 3 2012-01-03 50.89114
# 4 2012-01-04 50.59598
# 5 2012-01-05 51.63562
# 6 2012-01-06 50.68928

ggplot(df, aes(x=yday(date), y=value, color=factor(year(date)))) +
  geom_line()

生成此图的方法:

有哪些方法可以使轴按月格式化为日期?如果可能的话,我正在尝试确定一种同时利用 lubridatescale_x_date 的干净方法?

也许有更好的方法来创建这种类型的图表?也就是说,按年创建因素并将它们相互叠加? (注意:我不想在这个例子中使用 facet_wrapfacet_grid)。

一个解决方案可能是在您的数据框中添加一列,其中每一行包含另一年的日期和月份(所有行都相同),例如 2015 年。

df$days<-as.Date(format(df$date,"%d-%m-2015"),format="%d-%m-%y")

然后您可以使用此列作为 x

进行绘图
library(scales)
ggplot(df, aes(x=days, y=value, color=factor(year(date)))) +
  geom_line()+scale_x_date(labels = date_format("%b"))

编辑:简化了 df$days