将R中的地块另存为GIF [英] Saving plots in R as GIFs
本文介绍了将R中的地块另存为GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
savePlot
将图形保存到图像文件中。但我的同事只能打开.jpgs和.gif(可能是因为他在度假,在手机上看电子邮件)。我讨厌创建jpeg,因为特别是盒子情节看起来非常难看(胡须模糊等)。但savePlot
函数仅支持以下类型:
type = c("wmf", "emf", "png", "jpg", "jpeg", "bmp",
"tif", "tiff", "ps", "eps", "pdf")
如何在R中保存GIF格式的绘图?
编辑:如果可能,理想的解决方案应该可以在不安装ImageMagick的情况下工作(这样R脚本就可以轻松移植)。
推荐答案
R没有原生的GIF图形驱动程序,基本上(完全?)由于GIF格式的专利产权负担,请参阅http://tolstoy.newcastle.edu.au/R/help/05/02/12809.html。
caTools
包中有一个函数(write.gif()
),但它是专门为写入图像而设计的。如果你想使用它,你必须做一些棘手的事情,首先将你的曲线图转换成图像(例如,另存为PNG,然后将其读回R作为图像)。例如:
png("myPlot.png")
plot(rnorm(1000),rnorm(1000))
dev.off()
library(png)
P1 <- readPNG("myPlot.png")
library(caTools)
write.gif(P1,"myPlot.gif")
showGIF <- function(fn) system(paste("display",fn))
showGIF("myPlot.gif")
unlink("myPlot.gif") ## clean up
?write.gif()
有很多我没有读过的关于颜色索引的内容,但这对于更复杂的图表可能很重要...
animation
包有saveGIF()
保存GIF的函数,但(1)它是为保存多帧动画(非常规图形)而设计的,(2)它是通过调用ImageMagick来实现的。
只需自己构造该函数就更容易了。
- 安装ImageMagick(http://imagemagick.org)
- 另存为PNG,然后使用ImageMagick进行转换。
例如:
png("myPlot.png")
plot(rnorm(1000),rnorm(1000))
dev.off()
system("convert myPlot.png myPlot.gif")
unlink("myPlot.png") ## clean up
showGIF("myPlot.gif")
unlink("myPlot.gif") ## clean up
当然,如果您想要经常使用它们,您可以在函数中使用它们中的任何一个。
更新:我在这上面花了一段时间,试图获得一个纯R解决方案,但还没有一个有效的解决方案。欢迎建议或编辑...
## needs ImageMagick: just for testing ...
showGIF <- function(fn) system(paste("display",fn))
主函数:
saveGIF <- function(fn,verbose=FALSE,debug=FALSE) {
require(png)
require(caTools)
tmpfn <- tempfile()
on.exit(unlink(tmpfn))
savePlot(tmpfn,type="png")
P1 <- readPNG(tmpfn)
dd <- dim(P1)
P1 <- aperm(P1,c(3,1,2),resize=TRUE) ## P1[,1,15]
dim(P1) <- c(dd[3],prod(dd[1:2]))
P1 <- t(P1)
if (verbose) cat("finding unique colours ...
")
P1u <- unique(P1)
rgbMat <- function(x) {
rgb(x[,1],x[,2],x[,3])
}
if (verbose) cat("creating colour index ...
")
pp <- paste(P1[,1],P1[,2],P1[,3],sep=".")
## make sure factor is correctly ordered
ind <- as.numeric(factor(pp,levels=unique(pp)))
if (verbose) cat("finding colour palette ...
")
if (nrow(P1u)>256) {
if (verbose) cat("kmeans clustering ...
")
kk <- kmeans(P1u,centers=256)
ind <- kk$cluster[ind]
pal <- rgbMat(kk$centers)
} else {
pal <- rgbMat(P1u)
}
## test:
if (debug) {
dev.new()
par(mar=rep(0,4))
image(t(matrix(ind-1,nrow=dd[1])),col=pal,axes=FALSE,ann=FALSE)
}
if (verbose) cat("writing GIF ...
")
indmat <- matrix(ind-1,nrow=dd[1])
storage.mode(indmat) <- "integer"
write.gif(indmat,fn,col=as.list(pal),scale="never")
}
X11.options(antialias="none")
image(matrix(1:64,nrow=8),col=rainbow(10))
saveGIF("tmp.gif",verbose=TRUE,debug=TRUE)
showGIF("tmp.gif")
这篇关于将R中的地块另存为GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文