user22119
user22119

Reputation: 727

How do I save plot images in R?

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?

Upvotes: 15

Views: 62631

Answers (2)

Marc in the box
Marc in the box

Reputation: 11995

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.

Upvotes: 21

Jd Baba
Jd Baba

Reputation: 6118

If you want to plot the png file use the following command:

dev.copy(png,"myfile.png",width=8,height=6,units="in",res=100)
dev.off()

you can change res value to higher value if you want to output high quality graphs.

If you want to save the file as pdf use the following command:

pdf("myfile.pdf",width=8,height=6)
dev.off()

Remember to change the width and height values as needed.

Upvotes: 5

Related Questions