How to save a plot as image on the disk?

2019-01-01 16:58发布

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.

11条回答
姐姐魅力值爆表
2楼-- · 2019-01-01 17:20

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

查看更多
何处买醉
3楼-- · 2019-01-01 17:24
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
查看更多
一个人的天荒地老
4楼-- · 2019-01-01 17:27

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.

查看更多
有味是清欢
5楼-- · 2019-01-01 17:28
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))

png(filename=plotpath)

plot(x,y, main= file)

dev.off()
查看更多
浅入江南
6楼-- · 2019-01-01 17:30

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
查看更多
登录 后发表回答