Using geom_rect for time series shading in R

后端 未结 4 1980
粉色の甜心
粉色の甜心 2020-12-02 23:45

I am trying to shade a certain section of a time series plot (a bit like recession shading - similarly to the graph at the bottom of this article on recession shading in exc

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 00:25

    Its a bit easier using annotate and also note that the bounds for the rectange can be specified as shown:

    ggplot(a_series_df, aes(month, big)) + 
        geom_line() +
        annotate("rect", fill = "red", alpha = 0.5, 
            xmin = 1924, xmax = 1928 + 11/12,
            ymin = -Inf, ymax = Inf) +
        xlab("time")
    

    This would also work:

    library(zoo)
    
    z <- read.zoo(a_series_df, index = 2)
    autoplot(z) + 
        annotate("rect", fill = "red", alpha = 0.5, 
            xmin = 1924, xmax = 1928 + 11/12,
            ymin = -Inf, ymax = Inf) + 
        xlab("time") +
        ylab("big")
    

    Either one gives this:

    enter image description here

提交回复
热议问题