Reputation: 99526
In R, if I have already create a plot on the screen, is there a way to write it to a file, without rerun the plotting code again?
Is the quality same as plotting to a file directly? (e.g. when saved to pdf, can get copiable text and scalable showing of the plot)
Thanks!
Upvotes: 4
Views: 381
Reputation: 7928
You can use the savePlot
function for plots from the graphics package or ggsave
for plots from ggplot2 package.
Edit from comment
savePlot
only saves plots from cairo X11 devices (in my system it says that there is a similar function of the same name in windows).
As Ben Bolker suggested one can use recordPlot
and replayPlot
I suppose one could do something like:
plot(1:10)
pl <- recordPlot()
png()
replayPlot(pl)
dev.off()
About the quality:
For savePlot
you will probably get worse quality, see the Details in ?savePlot. Also savePlot does not save pdf files.
For recordPlot
/replayPlot
it will be exactly the same since the plot is re-created to be stored and you can change all the arguments of the pdf
/png
/jpg
function you are using.
Upvotes: 4
Reputation: 4807
Yes, use dev2bitmap
plot(1:10)
dev2bitmap("test.png")
EDIT: Note that you need GhostScript installed. The above code ran fine on my machine (OSX 10.9.2) with 0 tinkering, and I'm pretty sure I never installed GS myself ... but it may have been installed with a larger package, etc, so YMMV.
Upvotes: 4