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.

Yang
  • 16,037
  • 15
  • 100
  • 142
  • 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. – Richie Cotton Aug 24 '11 at 10:57
  • 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. – Jeff Aug 24 '11 at 14:48
  • 1
    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.net – Jeff Aug 24 '11 at 14:56
  • @Jeff: your hint led me to an answer. Posting. – Yang Aug 24 '11 at 19:54

1 Answers1

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

Yang
  • 16,037
  • 15
  • 100
  • 142
  • Yang, this is fantastic! I had no idea Simon had written such a package! Thanks for the answer. – Jeff Aug 24 '11 at 20:04
  • Nice work. Do you know if there's a PDF equivalent to this method @Yang? – geotheory Dec 09 '14 at 10:41
  • @gottheory please pose a question and I'll post this solution https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/ unfortunately `png(NULL)` does not work. – Hedgehog Oct 12 '17 at 00:25
  • 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? – Bob Nov 02 '18 at 19:14