...I really dig the animation package! ..so here's the outcome of my firsts encounters with saveHTML() - I produced an animation with pre-existing images by utilizing the functions readJPEG() and rasterImage() from the R-packages jpeg and ReadImages.
Credit goes out to xingmowang (nzprimarysectortrade-blog) from whom I picked up the concept of putting images to the plot region of a graph produced with the animation-functions.
require(ReadImages)
require(animation)
require(jpeg)
setwd("C:\\Users\\Kay\\Documents\\R.Examples\\Animation")
x <- seq(from = -4, to = 4, by = 0.1)
xy <- data.frame(x = x, y = sin(x))
plot(xy$x, xy$y, type = "l")
nrow(xy)
for (i in 1:nrow(xy)){
jpeg(paste(getwd(),"\\", i, "_pic.jpg", sep = ""),
width = 10, height = 10, units = "in", res = 100)
plot(xy$x[1:i], xy$y[1:i], ylim = c(-1.1, 1.1), xlim = c(-4.1, 4.1),
col = 3, lwd = 4, type = "l")
dev.off()}
dir()
files <- dir()
print(pics <- files[grep(".jpg", files, ignore.case = T)])
pics <- pics[order(as.integer(sub("_.*", "", pics)))]
saveHTML({
for(i in pics){
tmp <- readJPEG(i)
par(bg = "thistle", mar = c(2, 2, 2, 2))
plot(c(0, 10), c(0,10), type="n",
bty="n", xlab="", ylab="",
yaxs ="i", xaxs = "i")
rasterImage(tmp, 0, 0, 10, 10)
}
},
img.name = "pic",
interval = 0.2,
htmlfile = "test.html",
outdir = getwd(),
title = "Demo",
autobrowse = FALSE,
description = c("This is an animtated curve\n",
"...you can describe it here"))
Hi Kay,
ReplyDeleteThanks for quoting me here. YiHui Xie is the man. Haha
A hint would be: instead of reading .jpeg files, you make the graphs in R directly,
i.e.,
x <- sin(seq(0,2*pi,len=50))
saveHTML({plot(x[1:i],type="l",
col="green")
},
...
)
I used read.jpeg simply because I just had these pictures and they cannot be produced using R.
Really like your blog!
Hi,
ReplyDeleteActually this was my point: to show how to use pre-existing images. And, as commented somewhere in the post, I just made up some fake pics for this purpose (as to have a "self-standing" script example..).
Thanks and best wishes,
KC