I plot a simple linear regression using R. I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)
There are two different questions: First, I am already looking at the plot on my monitor and I would like to save it as is. Second, I have not yet generated the plot, but I would like to directly save it to disk when I execute my plotting code.
In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:
Note that one must use
quote
, otherwise theplot(x)
call is run in the global environment andNULL
gets passed tobasesave()
.Like this
or this
or this
And probably others too. They're all listed together in the help pages.
For the first question, I find
dev.print
to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to diskYou can replace
pdf
with other formats such aspng
.This will copy the image exactly as you see it on screen. The problem with
dev.copy
is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands