Home > Software engineering >  Why geom_rect colours only first row of facet_wrap?
Why geom_rect colours only first row of facet_wrap?

Time:07-05

I am trying to get shaded rectangles on every even-numbered panel of my facet_wrap plot. However, when I use geom_rect, it produces the rectangles only on the second panel. I tried using annotate and geom_tile but with no success. I presume I am missing some simple detail here, probably related to the fact that my X variable is categorical and not numeric, but I am fighting this for a few hours already...

Here is my code:

even_numbers <- seq(2,nrow(df.plt),2)
ggplot(df.plt)   
  geom_rect(data = df.plt[even_numbers, ],
            xmin = even_numbers - 0.5, xmax = even_numbers   0.5,
            ymin = -Inf, ymax = Inf, alpha = 0.3, fill = 'grey')  
  geom_boxplot(aes(x = Cnd, y = nst, fill = Srs), position = position_dodge(0.9), outlier.shape = 1)   
  facet_wrap(vars(Grp), ncol=1)

And the resulting plot: non-shaded segments in first line

Here I change the ggplot so it contains geom_rect separately for close and far segments:

even_numbers <- seq(2,length(unique(df.tmp$Cnd)),2) # here the df.tmp[even_numbers, ] doesn't need to have all the combinations
ggplot(df.tmp)   
  geom_rect(data = df.tmp[df.tmp$Grp=="close", ][even_numbers, ],
            xmin = even_numbers - 0.5, xmax = even_numbers   0.5,
            ymin = -Inf, ymax = Inf, alpha = 0.3, fill = 'grey')   
  geom_rect(data = df.tmp[df.tmp$Grp=="far", ][even_numbers, ],
            xmin = even_numbers - 0.5, xmax = even_numbers   0.5,
            ymin = -Inf, ymax = Inf, alpha = 0.3, fill = 'grey')  
  geom_boxplot(aes(x = Cnd, y = nst, fill = Srs), position = position_dodge(0.9), outlier.shape = 1)   
  facet_wrap(vars(Grp), ncol=1)

As you can see below, it works now: enter image description here

As I mentioned earlier, I am still not sure why geom_rect did not work in the first place. In my solution, a separate geom_rect needs to be prepared for each segment, so it's definitely not a solution for a plot with many of them. I was trying to find a more elegant way, so one wouldn't have to bother how many segments or other groupings are declared.

  • Related