How do I save plot images in R?

偶尔善良 提交于 2020-06-24 08:21:25

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17476769/how-do-i-save-plot-images-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!