baptiste / gridExtra

Miscellaneous Functions for "Grid" Graphics
http://cran.r-project.org/web/packages/gridExtra/index.html
15 stars 4 forks source link

using arrangeGrob (2.0) inside functions #15

Closed Dahaniel closed 9 years ago

Dahaniel commented 9 years ago

Hi there, I just updated to gridExtra 2.0 and found some major changes to how it behaves and this affects the bahaviour of the functions I am using it in. Maybe you have some advice on how I could restore the "old behaviour".

e.g. using your grid.arrange example with arrangeGrob:

library(gridExtra)
library(grid)
library(ggplot2)
library(lattice)
p <- qplot(1,1)
p2 <- xyplot(1~1)
r <- rectGrob(gp=gpar(fill="grey90"))
t <- textGrob("text")

old behaviour:

when I woul call arrangeGrob(t, p, p2, r, ncol=2) from within a function it would display the plot or if I would assign the functions output to a variable (p <- myfunction()), the plot would be stored there and I could e.g. save the plot via ggsave(plot = p, file = p.pdf)

new behaviour:

when using p <- arrangeGrob(t, p, p2, r, ncol=2) and then executing p it returns:

TableGrob (2 x 2) "arrange": 4 grobs
  z     cells    name                       grob
1 1 (1-1,1-1) arrange        text[GRID.text.944]
2 2 (1-1,2-2) arrange             gtable[layout]
3 3 (2-2,1-1) arrange lattice[GRID.lattice.1040]
4 4 (2-2,2-2) arrange        rect[GRID.rect.943]

I can however return the plot from the function with plot(p) but I cannot redirect this output to a variable that executes the plot automatically anymore. Also ggsave() gives me an error:

Error in ggsave(plot = a, "a.pdf") : plot should be a ggplot2 plot

Is there a workaround to get back to the old behaviour somehow? I have to admit that I am not really experienced with gtable etc., that's why I love gridExtra so much ;)

Thanks in advance, Daniel

baptiste commented 9 years ago

There are two separate issues:

1- print() used to draw the results of arrangeGrob(), which was a design decision (reluctantly) inherited from lattice and ggplot2. The conventional way of displaying grid-based graphics is grid.draw(), and that's what gtable uses. So if you saved a grob g, and want to display it, use grid.draw(g) (possibly after grid.newpage() if you want a blank page below. Incidentally, ggplot2 recently gained a grid.draw method (in the dev version), so this will eventually get a bit more consistent.

BTW, plot(g) will produce some output, but meant for debugging only; you really want to use grid.draw().

2- ggsave() does some checking that the plot object is of class ggplot, which prevents its use for other grobs. arrangeGrob used to trick it with a fake "ggplot" class, but it wasn't a good strategy. Instead, I've finally convinced Hadley to remove the class check in ggsave, which you can get in the dev version of ggplot2.

Dahaniel commented 9 years ago

Okay great, thanks for that explanation, will change my function!