我正在尝试对时间序列图的某个部分进行着色(有点像经济衰退阴影 - 类似于底部的图表)这篇关于 Excel 中的经济衰退阴影的文章 https://research.stlouisfed.org/tips/200511/recession_bars.pdf)。我整理了一些可能很笨拙的示例来进行说明。
我首先创建一个时间序列,用 ggplot2 绘制它,然后想使用 geom_rect 提供阴影。但我的论点一定有问题。
a<-rnorm(300)
a_ts<-ts(a, start=c(1910, 1), frequency=12)
a_time<-time(a_ts)
a_series<-ts.union(big=a_ts, month=a_time)
a_series_df<-as.data.frame(a_series)
ggplot(a_series)+
geom_line(mapping=aes_string(x="month", y="big"))+
geom_rect(
fill="red",alpha=0.5,
mapping=aes_string(x="month", y="big"),
xmin=as.numeric(as.Date(c("1924-01-01"))),
xmax=as.numeric(as.Date(c("1928-12-31"))),
ymin=0,
ymax=2
)
请注意,我也尝试过,但也不起作用。
geom_rect(
fill="red",alpha=0.5,
mapping=aes_string(x="month", y="big"),
aes(
xmin=as.numeric(as.Date(c("1924-01-01"))),
xmax=as.numeric(as.Date(c("1928-12-31"))),
ymin=0,
ymax=2)
)