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'm trying to save a rather large ggpairs file. For some reason I can't get ggsave to work on my device (the file is created but it's blank no matter the plot, file type etc.) so I have been manually right clicking on save image as on the output.
However the resolution is so poor you can't read the correlation information as I've had to reduce the font size.
Appreciate any suggestions on how to get out a readable output.
TIPI_data<- vms_data[, c("cond","group_aff","personal_exp","outcomes","mechanics", "TIPI_O", "TIPI_C", "TIPI_E","TIPI_A","TIPI_N")]
ggpairs(TIPI_data, ggplot2::aes(colour=cond), upper = list(continuous = wrap("cor", size = 1.5)))
I don't know if this works for you, it worked for me. I have used this code to save as png with high resolution:
corrPlot <- ggpairs(df, diag=list(continuous="density"), axisLabels='show')
png(filename, height=1000, width=1000)
print(corrPlot)
dev.off()
I used this reference: https://github.com/tidyverse/ggplot2/issues/650#issuecomment-65086626
I am using Windows. When trying to plot a graph on png device, it fails with the error.
My code:
png("C:\\plot1.png", width = 480, height = 480, units = "px", bg = "white")
par(mar= c(4, 4, 2, 1))
hist(pwrcon$Global_active_power,col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)")
dev.off()
Error:
Error in png("C:\\plot1.png", width = 480, height = 480, units = "px", :
unable to start png() device
In addition: Warning messages:
1: In png("C:\\plot1.png", width = 480, height = 480, units = "px", :
unable to open file 'C:\plot1.png' for writing
2: In png("C:\\plot1.png", width = 480, height = 480, units = "px", :
opening device failed
Can anyone help me in getting this resolved?
Thanks in advance
I cannot explain why, but I once found that when the folder path in which my RStudio project was saved was a very long character string, the png device would fail. When I shortened the folder path it worked.
I had the same issue while working in an r-markdown document.
The issue in my case had something to do with viewing the Chunk Output Inline. When I switched to viewing the Chunk Output in Console, it worked just fine.
I got also this error: "Error in (function (filename = "Rplot%03d.png", width = 480, height = 480, :
unable to start png() device"
The name of the .Rmd file that I've been working on was containing some nonenglish characters, so removing them has been helpful in my case.
Had the same problem on a PC. The problem was that there was an antivirus program with "Safe files" enabled, which blocked Rstudio from creating graphics files. The antivirus didn't display any information when blocking, so it doesn't give you any clues really.
The filename C:\plot1.png contains a backslash (\) which is an escape character . This causes the error you are getting.
Change it to a slash (/)
png("C:/plot1.png", width = 480, height = 480, units = "px", bg = "white")
Or double the backslash (\\):
png("C:\\plot1.png", width = 480, height = 480, units = "px", bg = "white")
I received the error mentioned above
Error in (function (filename = "Rplot%03d.png", width = 480, height = 480, : unable to start png() device Calls: <Anonymous> ...
My issue was with the fig.width option in one of my R-code chunks of my R-markdown document and when the output was rendered as an html document. The fig.width was too large compared to the other fig.width options in other code-chunks. Again this was observed only when I attempted to render it as an html document, not as a powerpoint presentation.
Also met the similar issue in Windows 10, my R script is put in the same folder as RScript.exe, using the package ggplot2. However I got the message could not open file 'Rplot001.png'.
Finally found two ways to solve the problem:
Move the R script to any other folder except the folder RScript.exe located.
Set work directory using the command setwd("YourPath") first, then do other things.
I came across the same type of error, neither png nor jpg device could not open from ggplot2's ggsave command. The path contained an Å symbol which was stored as \305 when inserted in a variable describing the directory.
setwd(path) followed by ggsave(filename)for this directory variable did work in this case, but ggsave(paste(path, filename, sep="/") did not.
Replacing the Å with an A in my case could resolve the error.
One other problem could be that your Rstudio may have updated. I have encountered this problem while working inside R-markdown. Trying the code in a regular R script still works. Try saving the markdown as a new file. This should fix the problem temporarily.
Do not know of a long term solution.
I had the same error message. Turns out there was a typo in the path name.
Besides these problems, reinstalling ggplot and tydiverse from CRAN seemed to have worked for some, see here
I also had this error today when working in an RMarkdown notebook (it was fine yesterday). If I edit a chunk then try to run it I get this error. If I then save the notebook and try the chunk again it works. My working directory is a OneDrive folder. I wonder whether that may be an issue.
Having to save every after edit is not ideal, but a workaround.
I added "dev.off()
"before plot, the problem solved. The reason may be because of the previous device has not turn off yet.
This has been solved, but I thought I might add my answer if it makes someone's life easier.
Of course you can have your wd set to some short path (or path with no special characters): setwd("c/Users/John/My_r_project)
But I use R at work, thus my R project is saved on a common drive with super long path, and my working directory has to be long. A workaround was:
```{r setup, include=FALSE}
knitr::opts_chunk$set(
fig.path = "c/Users/John/My_r_project/figures" #make sure you create the folder first in Windows
)
```
And you can of course add other options there as well, such as: dpi = 300, echo = FALSE, ...
I had the same problem while running R in Jupyter notebook. I did a lot of Google searches and tried everything possible. The only way it worked for me was by restarting the kernel. But, restarting the kernel is not a good solution if you already have trained your models which took you a long time.
If you are trying to save the PNG image, make sure you have permission to create files in the destination folder. I've seen this error come up on a corporate network where full access had not been granted to the user.
The error usually means that the file cannot over accessed or overwritten, meaning that the file is in use or the file path is not writeable.
In the first case, just close the files you have open (e.g., in an image preview) and try again.
interestingly, also observed the error when in the UI 'tableOutput' was used and on the server side 'renderPlot'
I have seen this message, and find this is because the png file is occupied by another software or process.
So close the software or process, then restart rstudio.
I once also run into this problem. For me the first solution worked, but you might also want to check the other two options.
Restart R session. Tab Session > Restart R (Ctrl + Shift + F10)
Check working directory using getwd() and change it is necessary using setwd(path)
Don't forget to close the device using dev.off()
I've been fiddling around with a function in R, where, long story short, I have a for-loop, and at each step, I save a plot using png, then immediately readPNG so that I can extract RGB information. I then make a second plot, then readPNG this so I can compare the RGB of the two images.
The problem is that I keep getting an error message about being unable to start the png() device, or to open the file for writing, after a number of loops (can be as few as a handful of loops, or as many as a few thousand).
Here is really simplified code, but it has the bare essentials, and generates the error message:
testfun<-function(beg,fini)
{
library(png)
setwd("D://mydirectory")
for (i in beg:fini)
{
png("test.png",width=277,height=277) #candidate image
par(mai=c(0,0,0,0))
plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
xaxt="n",yaxt="n",frame.plot=F)
polygon(x=c(10,60,60),y=c(10,10,60),col="red")
graphics.off()
image<-readPNG("test.png")
#code where I get rgb values for original
png("test2.png",width=277,height=277) #candidate image with diferent params
par(mai=c(0,0,0,0))
plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
xaxt="n",yaxt="n",frame.plot=F)
polygon(x=c(10,60,60),y=c(10,10,60),col="blue")
graphics.off()
image<-readPNG("test2.png")
#code where I get rgb values for second image, and compare
}
}
And the error message:
Error in png("test.png", width = 277, height = 277) :
unable to start png() device
In addition: Warning messages:
1: In png("test.png", width = 277, height = 277) :
Unable to open file 'test.png' for writing
2: In png("test.png", width = 277, height = 277) : opening device failed
Originally I had graphics.off() as dev.off() but then thought maybe the loop was so fast that turning off one device wasn't fast enough before needing to be open again and it was getting 'confused' somehow. I also tried using Sys.sleep(0.1) after each graphics.off, but that didn't help either. Am I missing something stupid and obvious, or is this just a device bug?
I've had the same problem occur, although not in a loop situation. In my case, it was because I was pointing the .png output to a directory that did not exist.
png('./tweets/graphics/unique words.png', width=12, height=8, units='in', res=300)
Once I created the directory, and referenced it correctly, the error went away and I got my .png image.
I had this issue while saving plots in a loop also. #Dino Fire gave me a hint, my loop-generated file name contained an illegal character...
Ensure that the file name is legal (look for slashes, ampersands, apostrophes etc.)
For me, the reason readPNG() wasn't working was because I was running it from within a Rmd (RMarkdown) file.
As soon as I ran the code in the R console or a regular script, it worked immediately.
if you are using RStudio (or R) set working directory to where pictures are (.jpg, .png) . It should be a directory, not just (C:/).
getwd()
setwd("C:/RCode/Deep Learning/Downloads/")
getwd()