使用facet_grid从ggplot中提取单个图 [英] Extract single plot from ggplot with facet_grid
本文介绍了使用facet_grid从ggplot中提取单个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用ggplot和facet_grid
生成一些图并将其另存为对象.我的问题是我还想将每个子组(即每个构面)分别保存为一个对象.我的问题是,现在是否可以从facet_grid
提取单个构面并将其另存为对象?这是一些简单的代码:
I want to produce some plots using ggplot and facet_grid
and save the plot as an object. My problem is that I also want to save each subgroup (i.e. each facet) as an object separately. My question is now if you can extract a single facet from facet_grid
and save it as an object? Here is some simple code:
library(ggplot2)
ggplot(data = mtcars, aes(x = disp, y = mpg)) +
geom_point() +
facet_grid(. ~ am)
现在我想产生两个对象-一个用于am=0
,一个用于am=1
.
Now I'd like to produce two objects - one for am=0
and one for am=1
.
推荐答案
我不确定为什么不使用子集,但是可以从构面网格中提取各个构面.
I'm not sure why you wouldn't use subsetting, but you can extract individual facets from a facet grid.
library(ggplot2)
library(grid)
library(gtable)
p1 = ggplot(data = mtcars, aes(x = disp, y = mpg)) +
geom_point() +
facet_grid(. ~ am)
g1 = ggplotGrob(p1)
# Rows and columns can be dropped from the layout.
# To show the layout:
gtable_show_layout(g1)
# Which columns (and/or rows) to drop?
# In this case drop columns 5 and 6 to leave am = 0 plot
# Drop columns 4 and 5 to leave am = 1 plot
# am = 0 plot
g1_am0 = g1[,-c(5,6)]
grid.newpage()
grid.draw(g1_am0)
# am = 1 plot
g1_am1 = g1[,-c(4,5)]
grid.newpage()
grid.draw(g1_am1)
这篇关于使用facet_grid从ggplot中提取单个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文