Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting to a file in R

Tags:

r

I'm a complete newbie to R, and none of the introductions I've seen cover how to use R when all you've got is the command line and no windowing system. My data's on a server, and I'm working with it via ssh. In gnuplot, you can set your "display" to be a PNG file on disk. How do I plot something to a file on disk from R? R-2.9.1 on CentOS, if it matters. Thanks!

(Sorry if this is unusually basic, but I have the worst time Googling for quick answers with R. Cute name, impossible to search for.)

like image 416
Jenn D. Avatar asked Jul 28 '10 14:07

Jenn D.


People also ask

How do I plot a PNG in R?

To add a picture to a plot in base R, we first need to read the picture in the appropriate format and then rasterImage function can be used. The most commonly used format for picture in R is PNG. A picture in PNG format can be added to a plot by supplying the values in the plot where we want to add the picture.

How do I Export a plot in R?

(1) The first (and easiest) is to export directly from the RStudio 'Plots' panel, by clicking on Export when the image is plotted. This will give you the option of png or pdf and selecting the directory to which you wish to save it to.


2 Answers

Just to expand on Gnoupi answer, you also need to close the connection to the device with dev.off if you want the plot to be written to file.

For instance

pdf("mygraph.pdf")
plot(x, y, "l")
dev.off()
like image 74
nico Avatar answered Sep 21 '22 02:09

nico


Keep in mind that postscrpt(), pdf(), png(), and jpeg() have specific function parameters which can be used to customize the output.

For example:

postscript("filename.eps", horizontal=F, width=4, height=4, 
             paper="special", onefile=F)
plot(x)
dev.off()

check ?postscriptfor more information on the parameters that can be utilized.

Secondly, keep in mind that all commands that you want to be included in your saved plot should be executed prior to dev.off()

For example:

postscript("filename.eps", horizontal=F, width=4, height=4, 
             paper="special", onefile=F)
plot(x)    
text(5, 1, "This is a message for the aliens")
text(5, 0.5, "Pizza is tasty")
dev.off()

Another example:

regone <- glm(y ~ x1, data=mydata, family=...)
summary(regone)

postscript("filename.eps", horizontal=F, width=4, height=4, 
                 paper="special", onefile=F)
plot(x, y)
abline(regone)
dev.off()

Hope that helps.

like image 24
amathew Avatar answered Sep 21 '22 02:09

amathew