如何在R中绘制时间序列数据,根据因子数据改变背景?

如何在R中绘制时间序列数据,根据因子数据改变背景?,r,plot,ggplot2,time-series,R,Plot,Ggplot2,Time Series,假设我有一些时间序列数据,如下所示: df <- data.frame(Month=seq(1,12), Value = rnorm(12,0,1), Season = c('Winter', 'Winter', 'Spring', 'Spring', 'Spring', 'Summer', 'Summer',

假设我有一些时间序列数据,如下所示:

df <- data.frame(Month=seq(1,12),
                 Value = rnorm(12,0,1),
                 Season = c('Winter', 'Winter', 'Spring',
                            'Spring', 'Spring', 'Summer',
                            'Summer', 'Summer', 'Fall',
                            'Fall', 'Fall', 'Winter'))
在ggplot或基本图形中:

plot(Value~Month, data=df, type='l')
我想做的是强制叠加一个因素。我想根据x轴上的月份更改背景色。所以,在我的例子中,左边的1/6是,比如说冬天是白色的,然后右边的第三个是黄色的春天,然后第三个是红色的夏天,等等,直到最右边的1/12再次是白色


对于时间序列数据来说,这似乎应该是一件简单易行的事情,但在任何图形包中,我都找不到任何关于如何做到这一点的帮助。任何建议或见解将不胜感激

在base R中,您可以执行以下操作:

plot(Value~Month, type="n")
rect(df$Month-0.5, min(df$Value), df$Month+0.5, max(df$Value), col=df$Season, lty=0)
lines(Value~Month, data=df, type='l', col="orange", lwd=2)
ggplot(df, aes(Month, Value, Season)) + 
  geom_rect(aes(NULL, NULL, 
    xmin=Month-0.5, xmax=Month+0.5, 
    ymin=min(Value), ymax=max(Value), 
    fill=Season
  )) + 
  geom_line()
为可怕的底色方案致歉,我将在这里举例说明:

要在
ggplot2
中执行相同操作,可以执行以下操作:

plot(Value~Month, type="n")
rect(df$Month-0.5, min(df$Value), df$Month+0.5, max(df$Value), col=df$Season, lty=0)
lines(Value~Month, data=df, type='l', col="orange", lwd=2)
ggplot(df, aes(Month, Value, Season)) + 
  geom_rect(aes(NULL, NULL, 
    xmin=Month-0.5, xmax=Month+0.5, 
    ymin=min(Value), ymax=max(Value), 
    fill=Season
  )) + 
  geom_line()
产生以下结果:

plot(Value~Month, type="n")
rect(df$Month-0.5, min(df$Value), df$Month+0.5, max(df$Value), col=df$Season, lty=0)
lines(Value~Month, data=df, type='l', col="orange", lwd=2)
ggplot(df, aes(Month, Value, Season)) + 
  geom_rect(aes(NULL, NULL, 
    xmin=Month-0.5, xmax=Month+0.5, 
    ymin=min(Value), ymax=max(Value), 
    fill=Season
  )) + 
  geom_line()

这里是一个开始,使用
geom\u rect
,从以下位置复制:


季节
zoo
软件包为
ts
zoo
时间序列对象提供了
xblocks()
功能,以方便此类显示。参见
示例(“xblock”,package=“zoo”)