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
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
.
There are two closely-related questions, and an answer for each.
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:
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
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 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()
.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()