ggplot:从多面图中提取选定的子图 [英] 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)
如何仅使用 g1
中的内容从图 g1
中提取图 g2
,而不是再次从数据中生成图?/p>
How to extract the plot g2
from the plot g1
using only the content in g1
, instead of generating it again from data?
推荐答案
如果您查看 str(g1)
,它是一个列表,其中包含有关绘制内容的大量信息.第一个元素是 data
,您可以对其进行覆盖,从而有效地将 g1
更改为 g2
:
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
也就是说,重新绘制通常比直接弄乱ggplot对象内部更为简单.
That said, replotting is usually simpler than messing with ggplot object internals directly.
这篇关于ggplot:从多面图中提取选定的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!