使用 facet_grid 从 ggplot 中提取单个图

Extract single plot from ggplot with facet_grid

我想使用 ggplot 和 facet_grid 制作一些绘图并将绘图保存为对象。我的问题是我还想将每个子组(即每个方面)分别保存为一个对象。我现在的问题是,您是否可以从 facet_grid 中提取单个面并将其保存为对象?这是一些简单的代码:

library(ggplot2)

ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_grid(. ~ am)

现在我想生成两个对象 - 一个用于 am=0,一个用于 am=1

您可以对数据进行子集化并删除 facet 命令。

ggplot(data = subset(mtcars,am==0), aes(x = disp, y = mpg)) +
    geom_point() 

ggplot(data = subset(mtcars,am==1), aes(x = disp, y = mpg)) +
    geom_point() 

我意识到我没有回答你关于另存为对象的问题。 在 ggplot 代码之前添加一行:

tiff(file="firstfolder from working dir/next folder/ name.tiff",units="in",width=5,height=6,res=72)

您需要在剧情代码后添加 dev.off() 才能再次看到内容打印到您的计算机屏幕上。

您可以使用 png、pdf 等...用于不同的格式。

如果只是一次关闭,并且您使用的是 RStudio,则可以从图中手动导出 window。请参阅上方的“导出”按钮。

我不确定您为什么不使用子集化,但您可以从分面网格中提取各个分面。

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)