Search code examples
rggplot2facet-wrap

R ggplot facet_wrap with conditions


Can I change the background for some values for the faceting?

I have 50 plots in the faceting plot. I wonder if I can highlight some of them by changing the background for the selected plots.

Specifically, the picture below is my ggplot outcome right. I want to highlight 37& 42 by coloring their background as lightblue. I thought about using ifelse. But I am not sure how to define the control flow.

faceted plot

below is my code

axr_treat_ctrl %>%  
   ggplot(aes(x= year, y= mtopic,colour= Type,group=Type))+
  geom_line( )+
  geom_point( size= 1) +
  scale_y_continuous(breaks = extended_breaks(n = 5) )+
  scale_x_continuous(breaks = extended_breaks(n = 10) )+
  geom_vline(xintercept = 2005,linetype=2,color= "brown")+  
  geom_vline(xintercept = c(2010,2011,2017),linetype=3,color= "blue")+  
  labs(x= "x-axis",
      y ="y-axis ")+
  facet_wrap(~topicr )+
  guides(x = guide_axis(angle = 90))+
  theme(legend.position = "bottom")

 #     ifelse ( topicr==37, call( expr(panel.background = element_rect(fill = "lightblue"))),
 #            call( expr( panel.background = element_rect(fill = "white") )))  )


Solution

  • I think the best way to do this is by manipulating your dataframe directly, axr_treat_ctrl. Here's a simple, separate example because your example isn't reproducible.

    library(ggplot2)
    
    mtcars <- data.frame(mtcars)
    
    mtcars$mazda <- ifelse(grepl("Mazda",rownames(mtcars)),1,0)
    
    ggplot(mtcars,aes(x=wt,y=mpg)) +
      geom_rect(aes(fill=mazda),xmin = -Inf,xmax = Inf,
                ymin = -Inf,ymax = Inf,alpha=0.2) +
      geom_point() +
      facet_wrap(~rownames(mtcars)) +
      theme(legend.position="none")
    

    In this example, I want to have a separate plot for each car build and then color the background of the cars with a Mazda build. Thus, I add a simple binary indicator variable called mazda that determines whether the observation is a Mazda car. I then pass the mazda variable into geom_rect. And the output:

    enter image description here

    Removed the legend per the comment from @camille. You can also maybe pass fill=factor(mazda) instead of just mazda to get a discrete legend, depends on what you're looking for.