R 没有本机 GIF 图形驱动程序,主要(完全?)由于 GIF 格式的专利负担:请参阅http://tolstoy.newcastle.edu.au/R/help/05/02/12809.html .
里面有一个函数caTools
包裹 (write.gif()
)但它是专门为写入图像而设计的。如果你想使用它,你必须先做一些 hacky 将你的绘图转换为图像(例如保存为 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()
有很多关于颜色索引的内容我没有读过,但这对于更复杂的图表可能很重要......
The 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
当然,如果您想经常使用它们,您可以在函数中使用其中任何一个。
UPDATE:我花了更长的时间来尝试获得纯 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 ...\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=".")
## make sure factor is correctly ordered
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)
}
## 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 ...\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")