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

1

9

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.

Chalmers answered 24/8, 2011 at 6:49 Comment(4)
AFAIK, this isn't yet possible. It's a feature that periodically gets requested, though I believe it requires a substantial reworking of R's connection code, hence it hasn't been done so far.Anuska
Yes indeed, the R connections plot is history (I wrote it). However, I've heard some interesting reports from this year's useR that someone may try and sneak in a tiny opening to the connections interface.Arias
Also, there is an undocumented way to get at the raw image data from a Cairo device. It's just that someone needs to write a converter for it, be it png, jpeg, tiff, etc. You'll have to read the source code, but scope out the .image function in the Cairo package on rforge.netArias
@Jeff: your hint led me to an answer. Posting.Chalmers
C
12

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.]

Chalmers answered 24/8, 2011 at 19:58 Comment(4)
Yang, this is fantastic! I had no idea Simon had written such a package! Thanks for the answer.Arias
Nice work. Do you know if there's a PDF equivalent to this method @Yang?Loera
@gottheory please pose a question and I'll post this solution andrewheiss.com/blog/2016/12/08/… unfortunately png(NULL) does not work.Phthisis
This seemed really fantastic, but about 1/3 of the time, inconsistently, it produces an all-grey "image." I know another option for plotting to memory is to use magick; are there any others?Sofiasofie

© 2022 - 2024 — McMap. All rights reserved.