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.
If you use
ggplot2
the preferred way of saving is to useggsave
. First you have to plot, after creating the plot you callggsave
:The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to
ggsave
, notablywidth
,height
, anddpi
.If you want to keep seeing the plot in R, another option is to use
dev.copy
:If you reach a clutter of too many plot windows in R, use
graphics.off()
to close all of the plot windows.If you open a device using
png()
,bmp()
,pdf()
etc. as suggested by Andrie (the best answer), the windows with plots will not pop up open, just *.png, *bmp or *.pdf files will be created. This is convenient in massive calculations, since R can handle only limited number of graphic windows.However, if you want to see the plots and also have them saved, call
savePlot(filename, type)
after the plots are drawn and the window containing them is active.There are two closely-related questions, and an answer for each.
1. An image will be generated in future in my script, how do I save it to disk?
To save a plot, you need to do the following:
png()
,bmp()
,pdf()
or similardev.off()
Some example code for saving the plot to a
png
file:This is described in the (combined) help page for the graphical formats
?png
,?bmp
,?jpeg
and?tiff
as well as in the separate help page for?pdf
.Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.
Note that if your plot is made by either
lattice
orggplot2
you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.
This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace
pdf
with other filetypes such aspng
.If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
This could be converted to jpg/png as necessary