In R, how to plot into a memory buffer instead of a file?

╄→尐↘猪︶ㄣ 提交于 2019-12-28 22:01:08

问题


I'm using JRI to generate ggplot2 plots from Java. Currently I have to write plots to disk. How do I do this without going through files, i.e. just rendering the plots in memory?

I tried using the Cairo package to plot to a textConnection, but that doesn't work without the "R Connections Patch," which after some Googling turns out to be ancient history.


回答1:


Mostly from https://stat.ethz.ch/pipermail/r-devel/2010-August/058253.html.

library(Cairo)
library(png)
library(ggplot2)

Cairo(file='/dev/null')

qplot(rnorm(5000)) # your plot

# hidden stuff in Cairo
i = Cairo:::.image(dev.cur())
r = Cairo:::.ptr.to.raw(i$ref, 0, i$width * i$height * 4)
dim(r) = c(4, i$width, i$height) # RGBA planes
# have to swap the red & blue components for some reason
r[c(1,3),,] = r[c(3,1),,]
# now use the png library
p = writePNG(r, raw()) # raw PNG bytes

[Update: JRI can handle raws, you just need to use the REngine abstractions and not the JRI ones.]



来源:https://stackoverflow.com/questions/7171523/in-r-how-to-plot-into-a-memory-buffer-instead-of-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!