geom_rect on some panels of a facet_wrap

后端 未结 2 1300
执笔经年
执笔经年 2021-01-05 03:23

I am trying to get a shaded rectangle on the first three panels in my facet_wrap plot. However, when I use geom_rect for the job, it produces the r

相关标签:
2条回答
  • 2021-01-05 03:41

    Here is a solution that creates a new data frame with variable and then takes advantage of recycling in aes to generate the rectangle coordinates for each value in variable.

    ggplot(dfTemp) +
      geom_rect(
        data=data.frame(variable=factor(1:3)), 
        aes(xmin=as.Date('2011-02-01'), xmax=as.Date('2011-03-01'), ymin=-Inf, ymax=Inf), 
        alpha = 0.5, fill = 'grey') +
      geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
      facet_wrap(~variable , scale = 'free', ncol = 2)
    

    enter image description here

    0 讨论(0)
  • 2021-01-05 03:42

    There's a very simple way to do this:

    library(ggplot2)
    library(plyr)      # for .(...)
    ggplot(dfTemp) +
      geom_rect(subset= .(variable<4),aes(xmin = as.Date('2011-02-01', format = '%Y-%m-%d'),
                    xmax = as.Date('2011-03-01', format = '%Y-%m-%d'),
                    ymin = -Inf,
                    ymax = Inf), alpha = 0.2, fill = 'grey') +
      geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
      facet_wrap(~variable , scale = 'free', ncol = 1) 
    

    The only difference with your original code is the addition of subset=.(variable<4) to the call to geom_rect(...).

    0 讨论(0)
提交回复
热议问题