【发布时间】:2015-07-10 13:22:16
【问题描述】:
当在 ggplot2 中使用 facet 多年时,我希望在时间序列图的 x 轴上同时拥有 month 和 day。我的 MWE 如下:
set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2014/1/1"), "week")
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)
df$Year <- format(df$Date, "%Y")
df$Month <- format(df$Date, "%b")
df$Day <- format(df$Date, "%d")
df$MonthDay <- format(df$Date, "%d-%b")
p <- ggplot(data=df, mapping=aes(x=MonthDay, y=Y, shape=Year, color=Year)) + geom_point() +geom_line(aes(group = 1))
p <- p + facet_grid(facets = Year ~ ., margins = FALSE) + theme_bw()
print(p)
我尝试使用以下命令控制 x 轴标签
p + scale_y_continuous() + scale_x_date(labels = date_format("%d-%b"))
但它会引发以下错误消息。
Error: Invalid input: date_trans works with objects of class Date only
【问题讨论】:
-
感谢@G.Grothendieck 的评论和对我的问题的兴趣。使用
x=Date将不必要地在 x 轴上花费所有四年,这不是必需的。
标签: r ggplot2 time-series