Is there a way to save a grob directly to a rasterGrob?
Asked Answered
J

1

6

I'm drawing several ggplot2 objects and placing them on a grid.arrange inside a call to a 'pdf' device. I've found that the PDF performs about a billion times better (generates faster, renders faster) if I rasterize the plots first. So inside a parallel dlply loop, I'm using ggsave to write the ggplot2 as a PNG, then using readPNG to read it back in and rasterGrob to convert return it to the dlply. The dlply puts it into a list of grobs which grid.arrange then draws to the PDF device.

Some of this seems unwieldy, so in general, is there a better approach? But what really bugs me is writing the PNGs to disk when all I do with them is read them back in. Is there a way to save a grob directly to a rasterGrob?

plot.list <- dlply( ... {
        ggsave(filename= fname
               ,plot= my.plot
               ,device= "png" 
               ,scale = 1, width= 1.1, height= 2.125, units = "in" 
               ,dpi = dpi)

        # return it as a list of rasters
        rasterGrob(readPNG( source= fname, info= TRUE))
}
Jorrie answered 28/4, 2016 at 20:2 Comment(2)
Hmm. Doesn't look easy. This may be helpful: #7172023 . You would use the Cairo graphics device directly rather than going though ggsaveReactivate
I sympathise with the question (I've always wanted a way to rasterise a specific plot layer), but if you're rasterising the whole image I'm not sure what you gain by making a pdf as opposed to a png?Perorate
J
0

I ended up using the Cairo graphics device as outlined in @Yang 's In R, how to plot into a memory buffer instead of a file? answer suggested by @MrFlick

Jorrie answered 22/11, 2019 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.