Prradep
Prradep

Reputation: 5696

ggplot: extract selected subplots from faceted plot

I have the following data and a faceted plot generated from it.

# Data generation
dataPlot <- mtcars %>% select(mpg, wt, carb) %>% 
  group_by(carb) %>% mutate(N = n()) %>% data.frame()

# Original Faceted plot
g1 <- ggplot(dataPlot, aes(mpg, wt)) + geom_point() + 
  facet_wrap(~carb) + ggtitle("Original plot")

I would like to extract the following plot from the above plot. For comparison, I am generating it from the data itself.

# Refined plot with minimum 4 points
g2 <- ggplot(dataPlot %>% filter(N > 3), aes(mpg, wt)) + geom_point() + 
  facet_wrap(~carb) + ggtitle("Refined plot")

# Plots together
grid.arrange(g1, g2, ncol=2)

enter image description here

How to extract the plot g2 from the plot g1 using only the content in g1, instead of generating it again from data?

Upvotes: 2

Views: 1286

Answers (1)

alistaire
alistaire

Reputation: 43334

If you look at str(g1), it a a list with a bunch of information about what to plot. The first element is data, which you can override, effectively changing g1 into g2:

library(tidyverse)

g1 <- ggplot(mtcars, aes(mpg, wt)) + 
    geom_point() + 
    facet_wrap(~ carb) + 
    ggtitle("Original plot")


g1$data <- g1$data %>% group_by(carb) %>% filter(n() > 3)

g1

That said, replotting is usually simpler than messing with ggplot object internals directly.

Upvotes: 4

Related Questions