Using geom_rect for time series shading in R

后端 未结 4 1953
粉色の甜心
粉色の甜心 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:19

    To use geom_rect you need to define your rectangle coordinate through a data.frame:

    shade = data.frame(x1=c(1918,1930), x2=c(1921,1932), y1=c(-3,-3), y2=c(4,4))
    
    #    x1   x2 y1 y2
    #1 1918 1921 -3  4
    #2 1930 1932 -3  4
    

    Then you give ggplot your data and the shade data.frame:

    ggplot() + 
      geom_line(aes(x=month, y=big), color='red',data=a_series_df)+
      geom_rect(data=shade, 
                mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color='grey', alpha=0.2)
    

    enter image description here

提交回复
热议问题