How to save a plot as image on the disk? How to save a plot as image on the disk? r r

How to save a plot as image on the disk?


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:

  1. Open a device, using png(), bmp(), pdf() or similar
  2. Plot your model
  3. Close the device using dev.off()

Some example code for saving the plot to a png file:

fit <- lm(some ~ model)png(filename="your/file/location/name.png")plot(fit)dev.off()

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 or ggplot2 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 sourcing


2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.

dev.print(pdf, 'filename.pdf')

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 as png.


If you want to keep seeing the plot in R, another option is to use dev.copy:

X11 ()plot (x,y)dev.copy(jpeg,filename="plot.jpg");dev.off ();

If you reach a clutter of too many plot windows in R, use graphics.off() to close all of the plot windows.


If you use ggplot2 the preferred way of saving is to use ggsave. First you have to plot, after creating the plot you call ggsave:

ggplot(...)ggsave("plot.png")

The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave, notably width, height, and dpi.