359

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.

0

11 Answers 11

433

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.

5
  • 5
    if you not set the path, like png(filename="name.png"), you can know the directory of save with getwd()
    – JuanPablo
    Commented Jul 15, 2013 at 18:51
  • 2
    I have extended this answer to include a reference to dev.print. There are two closely-related questions which I think need different answers. The second sub-question is basically "How do I save an image that I have already plotted to my screen?". Apologies if my editting isn't very good, feel free to improve on my edits. Commented Aug 27, 2015 at 10:08
  • How do I do this when R asks for a "Selection"? For example If I use m3=garchFit(~arma(3,0)+garch(1,1)) and plot(m3).
    – jacob
    Commented Jan 25, 2016 at 13:28
  • 3
    How can I save the figure with dpi=3000
    – Abhishek
    Commented Oct 25, 2017 at 12:57
  • 2
    8 years using R without knowing I could actually save the dev opened on my screen in a file. I guess I didn't need that... but thanks a lot :D
    – Simon C.
    Commented Oct 10, 2018 at 5:48
95

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.

3
  • 2
    Great answer! This allows you to experiment with plots via X, until you're happy with the results, and then save them on the spot. This is usually the most convenient mode of operation. Commented Nov 8, 2013 at 14:06
  • 3
    dev.print is better as it copies the image from the screen exactly. dev.copy forces every image to be square by default. This is frustrating if you've set up everything nicely interactively Commented Sep 2, 2014 at 8:19
  • 5
    I use dev.print() with the width and height parameters to define the dimensions. e.g. dev.copy(device = png, filename = 'MyPlot.png', width = 1000, height = 500) dev.off()
    – Scott
    Commented Apr 2, 2015 at 1:01
86

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.

5
  • This works well in a loop, dev.off didn't work for me Commented Jan 18, 2017 at 13:23
  • the upside of this is the consistent API and no need to mess with turning on and off devices
    – qwr
    Commented Apr 3, 2019 at 19:35
  • 1
    Unlike solutions with dev, this solution worked on a virtual machine without graphic devices.
    – emonigma
    Commented May 29, 2019 at 13:04
  • I wish there was a powerful, yet simple, approach like this for ALL plots in R. Anyway, my vote goes here.
    – SilSur
    Commented Jul 4, 2019 at 14:53
  • 1
    Still valid almost 7 Years on! Thank you.
    – Nick
    Commented Sep 3, 2019 at 4:39
31

Like this

png('filename.png')
# make plot
dev.off()

or this

# sometimes plots do better in vector graphics
svg('filename.svg')
# make plot
dev.off()

or this

pdf('filename.pdf')
# make plot
dev.off()

And probably others too. They're all listed together in the help pages.

1
  • 1
    Is there any way for R to infer the file extension automatically (i.e. based on the function)? It seems tedious to have to change the filename as well as the function used.
    – Bonlenfum
    Commented Nov 4, 2015 at 17:25
12

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 disk

dev.print(pdf, file="filename.pdf");

You can replace pdf with other formats such as png.

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

pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor
8

If you use RStudio, there is a special menu to save your plot as any format you like and at any resolution you choose.

2
  • 4
    This also exists in the R GUI on Windows, at least. Commented Sep 1, 2011 at 12:30
  • sometimes this mysteriously fails for me, but calling a function always works
    – qwr
    Commented Apr 3, 2019 at 19:34
4

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.

3
plotpath<- file.path(path, "PLOT_name", paste("plot_", file, ".png", sep=""))

png(filename=plotpath)

plot(x, y, main=file)

dev.off()
1
0

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 noninteractive 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.:

R < myscript.R --no-save

This could be converted to JPEG or PNG as necessary.

0

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:

x = 1:10

basesave = function(expr, filename, print=T) {
  #extension
  exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]

  switch(exten,
         png = {
           png(filename)
           eval(expr, envir = parent.frame())
           dev.off()
         },
         {stop("filetype not recognized")})


  #print?
  if (print) eval(expr, envir = parent.frame())

  invisible(NULL)
}

#plots, but doesn't save
plot(x)

#saves, but doesn't plot
png("test.png")
plot(x)
dev.off()

#both
basesave(quote(plot(x)), "test.png")

#works with pipe too
quote(plot(x)) %>% basesave("test.png")

Note that one must use quote, otherwise the plot(x) call is run in the global environment and NULL gets passed to basesave().

-1
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
3
  • An explanation would be in order. Commented Oct 30, 2023 at 18:11
  • OK, the OP has left the building: "Last seen more than 2 years ago" Commented Oct 30, 2023 at 18:12
  • Perhaps somebody else can chime it? Is this a bogus answer or not? Commented Oct 30, 2023 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.