Skip to content

Instantly share code, notes, and snippets.

@dill
Last active February 23, 2017 16:55
Show Gist options
  • Save dill/6c2fd466dad400c39800 to your computer and use it in GitHub Desktop.
Save dill/6c2fd466dad400c39800 to your computer and use it in GitHub Desktop.
Animations of uncertainty in density maps
# little animation to illustrate uncertainty in a density map
library(dsm)
library(mvtnorm)
library(ggplot2)
library(animation)
library(viridis)
# load the models and prediction data
# using data from the Duke spatial distance sampling course
# http://distancesampling.org/workshops/duke-spatial-2015/practicals.html
# models of sperm whales off the east coast of the US
load("sperm-data/count-models.RData")
load("sperm-data/predgrid.RData")
# ignoring detection function uncertainty for now...
# get the Lp matrix
Lp <- predict(dsm.nb.xy, newdata=predgrid, type="lpmatrix")
# how many realisations do we want?
frames <- 100
# generate the betas from the GAM "posterior"
betas <- rmvnorm(frames, coef(dsm.nb.xy), vcov(dsm.nb.xy))
# use a function to get animation to play nice...
anim_map <- function(){
# loop to make plots
for(frame in 1:frames){
# make the prediction
predgrid$preds <- predgrid$off.set * exp(Lp%*%betas[frame,])
# plot it (using viridis)
p <- ggplot(predgrid) +
geom_tile(aes(x=x,y=y,fill=preds), width=sqrt(1e8), height=sqrt(1e8)) +
scale_fill_viridis(limits=c(0,10))
print(p)
}
}
# make the animation!
ani.options(interval = 0.15)
saveGIF(anim_map(), outdir = "new")
@dill
Copy link
Author

dill commented Jan 19, 2016

Here is an example of an animation:
animation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment