How to Save a Plot as Image on the Disk

How to save a plot as image on the disk?

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:

  1. Open a device, using png(), bmp(), pdf() or similar
  2. Plot your model
  3. 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.

Save plot to image file instead of displaying it using Matplotlib

When using matplotlib.pyplot.savefig, the file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

That gives a rasterized or vectorized output respectively.
In addition, there is sometimes undesirable whitespace around the image, which can be removed with:

plt.savefig('foo.png', bbox_inches='tight')

Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.

Save a plot as a png image

Specify output path and file name by paste0ing output_dir and the other variables. You probably need a "/" at the end of your output_dir. Note, that in paste0 there is no sep= argument, sep='' is actually default. If p is already a plot (as I assume from your image) don't use plot(p) but print(p), or just p.

Just make it in two steps for training.

## 1. make string
output_dir <- "D:/data/results/images/" ## note the extra slash at the end

mla <- 'foo'
var <- 'bar'
cm <- 'baz'

(to <- paste0(output_dir, "/PICP_", mla, "_", var, cm, ".png", sep=""))
# [1] "D:/data/results/images/PICP_foo_barbaz.png" ## specified path

## 2. put string in `png` as filenmame
png(to, width=6, height=5, units="in", res=1200)

print(p) ## or just `p`

dev.off()

Note: If you just want "PICP.png" as filename,

to <- paste0(output_dir, "PICP.png")

is sufficient.


Data:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point()

How to save a plot as image on disk from Viewer in RStudio?

The answer turned out to be in the webshot package. @hrbrmstr provided the following code, which would be run at the end of the code I posted in the question:

# If necessary
install.packages("webshot")
library(webshot)
install_phantomjs()

# Main code
myChart$save("/tmp/rcharts.html")
webshot::webshot("/tmp/rcharts.html", file="/tmp/out.png", delay=2)

This saves the plot to the folder as an html, and then takes a picture of it, which is saved as a png.

I can then run the ReporteRs workflow by using addImage(mydoc, "/tmp/out.png").

How to save figure in Matplotlib in Python

pyplot keeps track of the "current figure", and functions called on the library which require a figure operate on that, but you can also be more explicit by calling savefig() on the figure object.

as an example from https://pythonspot.com/matplotlib-save-figure-to-image-file/:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()

fig.savefig('plot.png')

Being explicit in this way should solve your issue.

For references to pyplot functions which operate on the "current figure" see: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html

How to save a Highcharter plot as an image on local disk?

This should be possible with the webshot package (see question here: https://github.com/jbkunst/highcharter/issues/186)

library(webshot)
library(highcharter)
library(plyr)

data("citytemp")

plot <- highchart() %>%
hc_add_series(name = "London", data = citytemp$london, type = "area") %>%
hc_rm_series(name = "New York")

htmlwidgets::saveWidget(widget = plot, file = "~/plot.html")
setwd("~")
webshot::webshot(url = "plot.html",
file = "plot.png")

R: How to save an image(..) on disk?

Try without the call to x11():

library("maptools")
jpeg(file = "ram_artichoke2.jpg")

par(mar=c(2,2,2,2))
#image(lon,lat,artichoke_mat,col = grey(seq(1, 0, length = 256)))
data(wrld_simpl)
plot(wrld_simpl)
dev.off()

This worked for me but I did not have your data for lat and lon and artichoke_mat to add in the data points of interest.

Export plot to disk with predefined size, R

R's graphics devices have width and height arguments, that can be set to specified values.

Here is an example with device png().

png(filename = "mtcars.png", width = 1000, height = 746)

plot(mpg ~ hp, mtcars)
abline(lm(mpg ~ hp, mtcars), col = "blue", lty = "dashed")

dev.off()

How do I save plot images in R?

baptiste is on the right track with their suggestion of png for a nice raster type plot. In contrast to Jdbaba's suggestion of copying the open device, I suggest that you make a call to the png()device directly. This will save a lot of time in that you won't have to load the plot in a separate device window first, which can take a long time to load if the data set is large.

Example

#plotting of 1e+06 points
x <- rnorm(1000000)
y <- rnorm(1000000)
png("myplot.png", width=4, height=4, units="in", res=300)
par(mar=c(4,4,1,1))
plot(x,y,col=rgb(0,0,0,0.03), pch=".", cex=2)
dev.off() #only 129kb in size

Sample Image

see ?png for other settings of the png device.



Related Topics



Leave a reply



Submit