d8aninja
d8aninja

Reputation: 3643

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

Upvotes: 1

Views: 1190

Answers (2)

Quinnan Gill
Quinnan Gill

Reputation: 70

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

Upvotes: 3

Jon Spring
Jon Spring

Reputation: 66570

If you really want to show different plots on different facets, one hacky way would be to make separate copies of the data and subset those...

mpg2 <- mpg %>% mutate(facet = 1) %>%
  bind_rows(mpg %>% mutate(facet = 2))

ggplot(mpg2, aes(displ, cyl, color = drv)) +
  geom_point(data = subset(mpg2, facet == 1)) +
  geom_smooth(data = subset(mpg2, facet == 2)) +
  facet_wrap(~facet)

enter image description here

Upvotes: 2

Related Questions