Search code examples
rggplot2facet-wrapfacet-grid

How do I facet by geom / layer in ggplot2?


I'm hoping to recreate the gridExtra output below with ggplot's facet_grid, but I'm unsure of what variable ggplot identifies with the layers in the plot. In this example, there are two geoms...

require(tidyverse)

a <- ggplot(mpg)
b <- geom_point(aes(displ, cyl, color = drv))
c <- geom_smooth(aes(displ, cyl, color = drv))
d <- a + b + c

# output below
gridExtra::grid.arrange(
  a + b,
  a + c,
  ncol = 2
) 

# Equivalent with gg's facet_grid
# needs a categorical var to iter over...
d$layers
#d + facet_grid(. ~ d$layers??)

The gridExtra output that I'm hoping to recreate is:

enter image description here


Solution

  • A hacky way of doing this is to take the existing data frame and create two, three, as many copies of the data frame you need with a value linked to it to be used for the facet and filtering later on. Union (or rbind) the data frames together into one data frame. Then set up the ggplot and geoms and filter each geom for the desired attribute. Also for the facet use the existing attribute to split the plots.

    This can be seen below:

    df1 <- data.frame(
          graph = "point_plot",
          mpg
        )
    df2 <- data.frame(
        graph = "spline_plot",
        mpg
      )
    
    df <- rbind(df1, df2)
    
    ggplot(df, mapping = aes(x = displ, y = hwy, color = class)) +
      geom_point(data = filter(df, graph == "point_plot")) +
      geom_smooth(data = filter(df, graph == "spline_plot"), se=FALSE) +
      facet_grid(. ~ graph)
    

    enter image description here