Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save plot images in R?

Tags:

plot

r

save

I have created a plot from a very large vector (magnitude of 10^7). The problem with the usual way of saving the plot as a pdf file is that the pdf file comes out as a very large file of around 10MB. I don't want such a large size for a simple time series plot. How do I save the plot such that the size is small enough to be at most 100kilobytes?

like image 727
user22119 Avatar asked Jul 04 '13 19:07

user22119


People also ask

How do you save an image in R?

If you're running R through Rstudio, then the easiest way to save your image is to click on the “Export” button in the Plot panel (i.e., the area in Rstudio where all the plots have been appearing). When you do that you'll see a menu that contains the options “Save Plot as PDF” and “Save Plot as Image”.

Can plots be exported as image files or other file formats in R?

You can export your plots in many different formats but the most common are, pdf, png, jpeg and tiff. By default, R (and therefore RStudio) will direct any plot you create to the plot window. To save your plot to an external file you first need to redirect your plot to a different graphics device.

How do I save a Ggplot file as a PNG?

You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot. The default of ggsave() is to export the last plot that you displayed, using the size of the current graphics device. It also guesses the type of graphics device from the extension.


1 Answers

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

enter image description here

see ?png for other settings of the png device.

like image 176
Marc in the box Avatar answered Oct 16 '22 13:10

Marc in the box