Extract single plot from ggplot with facet_grid

强颜欢笑 提交于 2019-12-06 02:21:08

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)

You could subset your data on way in and remove the facet command.

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() 

I realized I didn't answer your question about saving as object. Before the ggplot code add a line :

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

You will need to add dev.off()after the plot code to see stuff print to your computer screen again.

You can use png, pdf, etc...for different formats.

If it is just a one off, and you are using RStudio, you can export manually from the plot window. See Export button above it.

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