0 votes
1 view
in R Programming by (19k points)

I am trying to plot multiple plots using ggplot2, arranging them using grid.arrange(). Since I managed to find someone describing the exact problem I have, I have quoted from the problem description from link:

When I use ggsave() after grid.arrange(), i.e.



I do not save the grid plot but the last individual ggplot. Is there any way of actually saving the plot as displayed by grid.arrange() using ggsave() or something similar? Other than using the older way




The same link gives the solution below:



p <- arrangeGrob(qplot(1,1), textGrob("test"))

grid.draw(p) # interactive device

ggsave("saving.pdf", p) # need to specify what to save explicitly

However, I can't figure out how to use ggsave() to save the output of the grid.arrange() call in the following code, which is taken from link:



dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

p1 <- qplot(carat, price, data=dsamp, colour=clarity)

p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")


tmp <- ggplot_gtable(ggplot_build(a.gplot))

leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")

legend <- tmp$grobs[[leg]]


legend <- g_legend(p1)

lwidth <- sum(legend$width)

## using grid.arrange for convenience

## could also manually push viewports

grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),

                                        p2 + theme(legend.position="none"),

                                        main ="this is a title",

                                        left = "This is my global Y-axis title"), legend, 

                     widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)

# What code to put here to save output of grid.arrange()?

1 Answer

0 votes
by (33.2k points)

You can use grid.arrange method, that can draw directly on a device.

You can also use arrangeGrob, that doesn't draw anything but returns a grob g, that you can pass to

ggsave(file="whatever.pdf", g).

The reason it works differently than with ggplot objects, where by default the last plot is being saved if not specified, is that ggplot2 invisibly keeps track of the latest plot, and I don't think grid.arrange should mess with this counter private to the package.

Hope this answer helps you!

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !