6

I'm trying to capture the result of a ggplot2 graphic creation in memory, to send it to a server. Has anyone a good idea how to solve that?

My code looks currently like this:

data(mtcars)
x <- ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point(shape=1)
print(x) # RStudio can capture the output, but I'm unable to do it.
ggsave(filename="a.jpg", plot=x) # not really a solution, need it not on disk, but as blob in memory.
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85
  • 3
    What kind of a blob? Binary bitmap? ggplot list? To be consumed by what program? – Mike Wise Oct 02 '15 at 11:56
  • @MikeWise The consumer is a program which accepts a python stringIO result - so it's just the content of a png read as "test" – Christian Sauer Oct 02 '15 at 12:09
  • I'm not sure if this will work, but maybe you can take advantage of SQLite's `BLOB` type - e.g. as in [this blog post](http://jfaganuk.github.io/2015/01/12/storing-r-objects-in-sqlite-tables/). – nrussell Oct 02 '15 at 13:01
  • Would encoding the graphic into a base64 string be useful? The resulting character string could then be sent elsewhere. – Peter Dec 15 '17 at 19:36
  • Possible duplicate of [In R, how to plot into a memory buffer instead of a file?](https://stackoverflow.com/questions/7171523/in-r-how-to-plot-into-a-memory-buffer-instead-of-a-file) – mlt Dec 04 '18 at 23:31

1 Answers1

1

You can do this with the magick package.

library(magick)
data(mtcars)
x <- ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point(shape=1)
fig <- image_graph(width = 400, height=400, res=96)
print(x)
dev.off()
figpng <- image_write(fig, path=NULL, format="png")

figpng is now a raw vector of a png of your plot.

Bob
  • 1,274
  • 1
  • 13
  • 26