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

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.

This question is related to r plot ggplot2 lattice r-faq

The answer is


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

R < myscript.R --no-save

This could be converted to jpg/png as necessary


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.


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

png(filename=plotpath)

plot(x,y, main= file)

dev.off()

dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()

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

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.


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


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().


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.


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.


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to plot

Fine control over the font size in Seaborn plots for academic papers Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python Modify the legend of pandas bar plot Format y axis as percent Simple line plots using seaborn Plot bar graph from Pandas DataFrame Plotting multiple lines, in different colors, with pandas dataframe Plotting in a non-blocking way with Matplotlib What does the error "arguments imply differing number of rows: x, y" mean? matplotlib get ylim values

Examples related to ggplot2

Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Remove legend ggplot 2.2 Remove all of x axis labels in ggplot Changing fonts in ggplot2 Explain ggplot2 warning: "Removed k rows containing missing values" Error: package or namespace load failed for ggplot2 and for data.table In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

Examples related to lattice

How to plot a function curve in R How to save a plot as image on the disk?

Examples related to r-faq

What does "The following object is masked from 'package:xxx'" mean? What does "Error: object '<myvariable>' not found" mean? How do I deal with special characters like \^$.?*|+()[{ in my regex? What does %>% function mean in R? How to plot a function curve in R Use dynamic variable names in `dplyr` Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning? How to select the row with the maximum value in each group R data formats: RData, Rda, Rds etc