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.
5
  • 3
    What kind of a blob? Binary bitmap? ggplot list? To be consumed by what program? Commented Oct 2, 2015 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" Commented Oct 2, 2015 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. Commented Oct 2, 2015 at 13:01
  • Would encoding the graphic into a base64 string be useful? The resulting character string could then be sent elsewhere. Commented Dec 15, 2017 at 19:36
  • Possible duplicate of In R, how to plot into a memory buffer instead of a file? Commented Dec 4, 2018 at 23:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.