Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

r - Store output from gridExtra::grid.arrange into an object

I am placing multiple plots into one image using gridExtra::grid.arrange and would like to have the option of saving the combined plot as an object that could be returned from within a function as part of a list of returned objects. Ideally, I would like to do this without printing the plot object.

The code below creates two plots, combines them with grid.arrange, and attempts to save the result into x. However, x evaluates to NULL and the plot is printed. The documentation for grid.arrange points me to arrangeGrob and suggests plotting can be turned off using plot=FALSE, but I get an error when I try that because FALSE is not a grob object.

Any suggestions for what I'm not understanding?

# R under development
# Windows 7 (32 bit)
# ggplot2 1.0.0
# gridExtra 0.9.1

p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()

p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()

x <- gridExtra::grid.arrange(p1, p2)

x

Per the comments, I'm adding this edit. When I try it with arrangeGrob, I get no output at all.

> gridExtra::arrangeGrob(p1, p2)
> print(gridExtra::arrangeGrob(p1, p2))
Error: No layers in plot
> x <- gridExtra::arrangeGrob(p1, p2)
> x
Error: No layers in plot
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code in your edit does not work properly since you didn't load gridExtra.

library(gridExtra)
y <- arrangeGrob(p1, p2, ncol = 1)
class(y)
#[1] "gtable" "grob"   "gDesc"
grid.draw(y)

enter image description here

Edit: since version 2.0.0, my comment about grid dependency below is no longer valid, since grid is now imported.

Edit: With gridExtra version >= 2.0.0, there is no need to attach either package,

p <- ggplot2::qplot(1,1)
x <- gridExtra::arrangeGrob(p, p)
grid::grid.draw(x)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...