R without displaying a graphics window

I need to save the plot object in a variable. I know what I can do:

plot(rnorm(10))
obj = recordPlot()
replayPlot(obj)

But I do not want to show the graphics window. So I'm trying to do it, but without success so far.

win.metafile()
plot(rnorm(10))
obj = recordPlot()
dev.off()
replayPlot(obj) # it shows a null plot

Well, probably because when I do the obj = recordPlot()plot is not ready yet.

+3
source share
2 answers

From ?recordPlot:

The displaylist can be turned on and off using dev.control. 
Initially recording is on for screen devices, and off for print devices.

So, you need to include the display list if you want to write the plot entry to a file:

win.metafile()
dev.control('enable') # enable display list
plot(rnorm(10))
obj = recordPlot()
dev.off()
replayPlot(obj)
+4
source

You can easily do this with ggplot2:

require(ggplot2)
data = data.frame(x = 1:100, y = rnorm(100))
p = ggplot(data) + geom_point(aes(x, y)) + theme_classic()
print(p) # this show the plot
0
source

All Articles