# Categorical sampling animation # (from Fig 11 of Wild et al's RSS article) # Data based on Census at School Table Maker # https://www.censusatschool.org.nz/2011/table-maker/?f1=travel&f2= modes <- c("walk", "car", "bus", "bike", "other") travel <- factor(rep(modes, c(7349, 8992, 6486, 1156, 263+311+384))) # Take many samples from the pop and tabulate them n <- 100 sn <- 100 samples <- lapply(1:n, function(i) { table(sample(travel, sn)) }) # Plot the samples (first as a barplot, all as horizontal bars) library(grid) library(lattice) boxWidth <- unit(2, "cm") barchart(samples[[1]], col=rgb(0,0,1,.2), ylim=c(0, max(sapply(samples, max))), horizontal=FALSE, box.width=boxWidth) # Add the horizontal bars trellis.focus("panel", 1, 1) count <- 1 samplefun <- function(samp) { grid.segments(unit(1:5, "native") - 0.5*boxWidth, unit(samp, "native"), unit(1:5, "native") + 0.5*boxWidth, unit(samp, "native"), gp=gpar(lwd=2, col=rgb(0,0,1,.2)), name=paste("sample.line", count, sep=".")) count <<- count + 1 } lapply(samples, samplefun) trellis.unfocus() # Animate the bar height library(gridSVG) time <- 10 grid.animate("plot_01.barchart.rect.panel.1.1", height=do.call("rbind", samples), # height=animUnit(unit(unlist(samples), "native"), # id=rep(1:5, n)), duration=time, interpolate="discrete") # Animate the visibility of the horizontal bars for (i in 1:n) { grid.garnish(paste("sample.line", i, sep="."), visibility="hidden") grid.animate(paste("sample.line", i, sep="."), visibility=c("hidden", "visible"), group=TRUE, begin=i/n*time, duration=.01) } gridToSVG("wild.svg")