In R, How to Plot into a Memory Buffer Instead of a File

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

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

In R, how to plot in SVG format and output to memory buffer instead of file

The gridSVG package might be useful:

library(ggplot2)
library(gridSVG)

ggplot(iris, aes(Species, Sepal.Length)) + geom_point()

SVGlist <- grid.export(name = NULL)
str(SVGlist, 1)
#List of 4
# $ svg :Classes 'XMLInternalElementNode', 'XMLInternalNode', 'XMLAbstractNode' <externalptr>
# $ coords :List of 18
# $ mappings:List of 5
# $ utils : chr "// Note that this code is documented using JSDoc and guided by the following URLs:\n// http://code.google.com/p/jsdoc-toolkit/w"| _truncated__

SVGlist$svg
#the SVG code

However, this still needs to print to the graphics device.

Create ggplot2 plot 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.

In R, How do I set plot size when plotting to raw png (byte array)

First, it is always helpful if you submit a working example.

Second, have you read the ?png?

Third, if you share your end goal it is easier for us to suggest possible solutions and understand your problem (maybe you can get out of running R in a Java program).

Here is how I would do it, though it does sound as you do not what the png on your hard disk?

png("mygraph.png",  width = 480, height = 480, units = "px")
plot(sin, -pi, 2*pi)
dev.off()

Let me know if this works for you or try to be more specific in your question.

Best, Eric

How to convert variable to RDA format in memory

This is possible with raw connections

rc <- rawConnection(raw(0),"wb")
save(iris,file=rc)
v1 <- rawConnectionValue(rc)
close(rc)

head(v1,80)
#> [1] 52 44 58 32 0a 58 0a 00 00 00 02 00 03 01 01 00 02 03 00 00
#> [21] 00 04 02 00 00 00 01 00 04 00 09 00 00 00 04 69 72 69 73 00
#> [41] 00 03 13 00 00 00 05 00 00 00 0e 00 00 00 96 40 14 66 66 66
#> [61] 66 66 66 40 13 99 99 99 99 99 9a 40 12 cc cc cc cc cc cd 40

Compare to writing to a temporary file and reading back

save(iris,file="temp.rda",compress=FALSE)
v2 = readBin("temp.rda", raw(), file.info("temp.rda")[1,"size"])

identical(v1,v2)
#> [1] TRUE

Note that writing to file by default uses compression and writing to a raw connection by default does not, hence the compress=FALSE argument.


See also serialize, which may be more suitable, depending on your purpose

v3 <- serialize(iris,NULL)

Note that identical(v1,v3)==FALSE. Indeed, v3 is identical instead to using saveRDS in place of save above. The encoding/content is similar

head(v3,80)
#> [1] 58 0a 00 00 00 02 00 03 01 01 00 02 03 00 00 00 03 13 00 00
#> [21] 00 05 00 00 00 0e 00 00 00 96 40 14 66 66 66 66 66 66 40 13
#> [41] 99 99 99 99 99 9a 40 12 cc cc cc cc cc cd 40 12 66 66 66 66
#> [61] 66 66 40 14 00 00 00 00 00 00 40 15 99 99 99 99 99 9a 40 12

And it is easy to recover the data

identical(unserialize(v3),iris)
#> [1] TRUE

Is there a way to read and write in-memory files in R?

It looks like ShortRead is soon to add a "FastqStreamer" class that does what I want.

Is there a way to save a grob directly to a rasterGrob?

I ended up using the Cairo graphics device as outlined in @Yang 's In R, how to plot into a memory buffer instead of a file? answer suggested by @MrFlick

how to save a pylab figure into in-memory file which can be read into PIL image?

Remember to call buf.seek(0) so Image.open(buf) starts reading from the
beginning of the buf:

import io
from PIL import Image
import matplotlib.pyplot as plt

plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
im.show()
buf.close()


Related Topics



Leave a reply



Submit