r - ggplot2中具有时间序列的月和日的日期序列在年份中具有方面

标签 r ggplot2 time-series

month中使用day时,我想在时间序列图的x轴上同时包含facetggplot2。我的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

最佳答案

你很亲密您希望x轴可以衡量您所在年份的位置,但是您可以将x轴用作字符向量,因此要标记每个点。如果改用连续变量表示这一点,则可能会有更好的结果。一个连续变量将是一年中的一天。

df$DayOfYear <- as.numeric(format(df$Date, "%j"))
ggplot(data = df,
       mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  theme_bw()




可以使用适当的标签功能将轴格式化为更类似日期的格式,但是仍然无法以非常了解日期的方式找到中断。 (最重要的是,还有一个NA问题。)

ggplot(data = df,
       mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  scale_x_continuous(labels = function(x) format(as.Date(as.character(x), "%j"), "%d-%b")) +
  theme_bw()




为了获得良好的日期间隔,可以使用其他变量。它与原始数据在一年中的同一天,但只有一年。在这种情况下,2000年是was年。与此相关的问题主要与leap日有关,但是如果您对此不关心(非-年的3月1日与a年的2月29日一致,等等),则可以使用:

df$CommonDate <- as.Date(paste0("2000-",format(df$Date, "%j")), "%Y-%j")
ggplot(data = df,
       mapping = aes(x = CommonDate, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  scale_x_date(labels = function(x) format(x, "%d-%b")) +
  theme_bw()

关于r - ggplot2中具有时间序列的月和日的日期序列在年份中具有方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974535/

相关文章:

r - 无法安装 gmum.r 包

r - 可以打印超过 100 行的 data.table 吗?

r - 接收面板比例/布局信息的刻面标签器功能

r - 在 ggplot2 生成的图下方显示文本

python - 如何根据索引在日期间隔之间的条件过滤数据框?

python - 分割数据集以按行进行训练和测试

r - 对于所有 block 是否有一个全局命令行 knit 选项 eval=FALSE ?

r - 处理data.frame列表时出现意外错误

r - ggplot2: geom_bar 堆叠条形图,指定条形轮廓颜色

time-series - pyqt图: how to plot time series (date and time on the x axis)?