6

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

Community
  • 1
  • 1
user3825755
  • 883
  • 2
  • 10
  • 29
  • 2
    Very interesting question, [the answer](https://stackoverflow.com/questions/9847559/conditionally-change-panel-background-with-facet-grid) to this post shows an alternative way to do it, is it enough for your needs ? – Paul Oct 11 '19 at 07:52
  • Another idea is to think your output as a bunch of single plots and then plot them together with `cowplot` package for example, but I think it's a tedious route. – s__ Oct 11 '19 at 08:01

1 Answers1

6

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

Paul
  • 2,850
  • 1
  • 12
  • 37