简体   繁体   中英

Create ggplot2 plot in memory?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM