ggplot: extract selected subplots from faceted plot

蹲街弑〆低调 提交于 2021-01-28 01:36:31

问题


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)

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


回答1:


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.



来源:https://stackoverflow.com/questions/48286995/ggplot-extract-selected-subplots-from-faceted-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!