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")
?write.gif()
中包含很多关于颜色索引的内容,我没有读过,但对于更复杂的图形可能很重要。
animation
包中有一个saveGIF()
函数来保存GIFs,但是(1)它设计用于保存多帧动画(而不是一般的图形),(2)它通过调用ImageMagick完成。
最简单的方法就是自己构造该函数。
例如:
png("myPlot.png")
plot(rnorm(1000),rnorm(1000))
dev.off()
system("convert myPlot.png myPlot.gif")
unlink("myPlot.png")
showGIF("myPlot.gif")
unlink("myPlot.gif")
当然,如果你想经常使用它们,你可以将它们放在一个函数中。
更新: 我花了更长时间来尝试得到一个纯R的解决方案,但是还没有找到一个可行的解决方案。欢迎提出建议或编辑...
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)
dim(P1) <- c(dd[3],prod(dd[1:2]))
P1 <- t(P1)
if (verbose) cat("finding unique colours ...\n")
P1u <- unique(P1)
rgbMat <- function(x) {
rgb(x[,1],x[,2],x[,3])
}
if (verbose) cat("creating colour index ...\n")
pp <- paste(P1[,1],P1[,2],P1[,3],sep=".")
ind <- as.numeric(factor(pp,levels=unique(pp)))
if (verbose) cat("finding colour palette ...\n")
if (nrow(P1u)>256) {
if (verbose) cat("kmeans clustering ...\n")
kk <- kmeans(P1u,centers=256)
ind <- kk$cluster[ind]
pal <- rgbMat(kk$centers)
} else {
pal <- rgbMat(P1u)
}
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 ...\n")
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")
animation
和caTools
都有保存gif的函数:请参见http://cran.r-project.org/web/packages/animation/animation.pdf和http://svitsrv25.epfl.ch/R-doc/library/caTools/html/GIF.html。此外,还可以在这里查看:http://tolstoy.newcastle.edu.au/R/help/05/02/12809.html。 - user1981275