Search code examples
rggplot2facet-grid

Highlight / Draw a box around some of the plots when using `facet_grid` in ggplot2


I am creating a matrix of plots similar to

ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(rows = vars(cyl), cols = vars(drv))

Now, I would like to have some way to highlight some of the individual plots, say the ones where cyl is 5 or 6, and drv is f. So, ideally, this might look like this:

enter image description here

But I would also be happy with those panels having a different look by setting ggtheme to classic or similar.

However, it is very unclear to me how I can modify individually selected plots within a matrix of plots generated via facet_grid


Solution

  • From @joran answer found here, this is what I get :

    [EDIT] code edited to select multiple facets

        if(!require(tidyverse)){install.packages("tidyverse")}
        library(tidyverse)
    
        #dummy dataset
    
        df = data.frame(type = as.character(c("a", "b", "c", "d")),
                        id = as.character(c("M5", "G5", "A7", "S3")),
                        val = runif(4, min = 1, max = 10),
                        temp = runif(4))
    
        # use a rectangle to individually select plots
    ggplot(data = df, aes(x = val, y = temp)) + 
      geom_point() +
      geom_rect(data = subset(df, type %in% c("b", "c") & id %in% c("A7","G5")), 
                              fill = NA, colour = "red", xmin = -Inf,xmax = Inf,
                ymin = -Inf,ymax = Inf) +
      facet_grid(type~id)
    

    It does not use theme() but it seems simple enough to highlight some facets.

    enter image description here