Related
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.
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:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
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.
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.
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 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
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.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
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
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().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
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.
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:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
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.
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.
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 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
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.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
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
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().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
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.
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:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
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.
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.
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 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
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.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
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
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().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
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.
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:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
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.
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.
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 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
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.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
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
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().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
I've made different plots (more than a hundred) for a project and I haven't capture them on the way (yes it's bad , i know). Now, I need to save them all at once but without running again my script (which takes hours). Is there a way to do so within Rstudio ?
Edit: All the plot are already there and I don't want to run them again.
In RStudio, every session has a temporary directory that can be obtained using tempdir(). Inside that temporary directory, there is another directory that always starts with "rs-graphics" and contains all the plots saved as ".png" files. Therefore, to get the list of ".png" files you can do the following:
plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE);
plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE)
Now, you can copy these files to your desired directory, as follows:
file.copy(from=plots.png.paths, to="path_to_your_dir")
Additional feature:
As you will notice, the .png file names are automatically generated (e.g., 0078cb77-02f2-4a16-bf02-0c5c6d8cc8d8.png). So if you want to number the .png files according to their plotting order in RStudio, you may do so as follows:
plots.png.detials <- file.info(plots.png.paths)
plots.png.detials <- plots.png.detials[order(plots.png.detials$mtime),]
sorted.png.names <- gsub(plots.dir.path, "path_to_your_dir", row.names(plots.png.detials), fixed=TRUE)
numbered.png.names <- paste0("path_to_your_dir/", 1:length(sorted.png.names), ".png")
# Rename all the .png files as: 1.png, 2.png, 3.png, and so on.
file.rename(from=sorted.png.names, to=numbered.png.names)
Hope it helps.
Although this discussion has been inactive for a while, there are some persons, like myself, who still come across the same problem, and the other solutions don't really seem to even get what the actual question is.
So, hands on. Your plot history gets saved in a variable called .SavedPlots. You can either access it directly, assign it to another variable in code or do the latter from the plots window.
# ph for plot history
ph <- .SavedPlots
In R 3.4.2, I could index ph to reproduce the corresponding plot in a device. What follows is rather straightforward:
Open a new device (png, jpeg, pdf...).
Reproduce your plot ph[index_of_plot_in_history].
Close the device (or keep plotting if it is a pdf with multiple pages).
Example:
for(i in 1:lastplot) {
png('plotname.png')
print(ph[i])
dev.off()
}
Note: Sometimes this doesn't happen because of poor programming. For instance, I was using the MICE package to impute many datasets with a large number of variables, and plotting as shown in section 4.3 of this paper. Problem was, that only three variables per plot were displayed, and if I used a png device in my code, only the last plot of each dataset would be saved. However, if the plots were printed to a window, all the plots of each dataset would be recorded.
If your plots are 3d, you can take a snapshot of all your plots and save them as a .png file format.
snapshot3d(filename = '../Plots/SnapshotPlots.png', fmt = 'png')
Or else, the best way is to create a multi-paneled plotting window using the par(mfrow) function. Try the following
plotsPath = "../Plots/allPlots.pdf"
pdf(file=plotsPath)
for (x in seq(1,100))
{
par(mfrow = c(2,1))
p1=rnorm(x)
p2=rnorm(x)
plot(p1,p2)
}
dev.off()
You can also use png, bmp, tiff, and jpeg functions instead of pdf. You can read their advantages and disadvantages and choose the one you think is good for your needs.
I am not sure how Rstudio opens the device where the plot are drawn, but I guess it uses dev.new(). In that case one quick way to save all opened graphs is to loop through all the devices and write them using dev.print.
Something like :
lapply(dev.list(),function(d){dev.set(d);dev.print(pdf,file=file.path(folder,paste0("graph_",d,".pdf"))})
where folder is the path of the folder where you want to store your graph (could be for example folder="~" if you are in linux and want to store all your graph in your home folder).
If you enter the following function all that will follow will be save in a document:
pdf("nameofthedocument.pdf")
plot(x~y)
plot(...
dev.off()
You can also use tiff(), jpg()... see ?pdf