Skip to content

Instantly share code, notes, and snippets.

@rmcelreath
Last active January 24, 2020 05:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmcelreath/86b2818ca2bc723946a57954a899d9c0 to your computer and use it in GitHub Desktop.
Save rmcelreath/86b2818ca2bc723946a57954a899d9c0 to your computer and use it in GitHub Desktop.
Code for Figure 2.5 on page 30 of Statistical Rethinking
## code to reproduce Figure 2.5 on page 30 of Statistical Rethinking
library(rethinking)
col1 <- "black"
col2 <- col.alpha( "black" , 0.7 )
# show posterior as data comes in
# 1 indicates 'water'; 0 indicates 'land'
d <- c(1,0,1,1,1,0,1,0,1) # length 9
l <- ifelse( d==1 , "W" , "L" )
par(mfrow=c(3,3)) # 3 by 3 grid
# make nicer margins
par(mgp = c(1.5, 0.5, 0), mar = c(2.5, 2.5, 2, 1) + 0.1, tck = -0.02 )
# prior uniform - "Laplace" prior
a <- 1
b <- 1
# draw plots
for ( i in 1:9 ) {
prior.a <- a
prior.b <- b
a <- a + d[i]
b <- b + 1 - d[i]
curve( dbeta(x,a,b) , from=0 , to=1 , xlab="probability of water" , ylab="" , col=col1 , lwd=2 , ylim=c(0,2.75) , xaxt="n" , yaxt="n" )
axis( 1 , at=c(0,0.5,1) , labels=c(0,0.5,1) )
text( 0.15 , 2.5 , paste("n =",i) )
curve( dbeta(x,prior.a,prior.b) , add=TRUE , col=col1 , lty=2 )
mtext( paste(l) , at=seq(from=0,to=1,length.out=length(l)) , col=c( rep(col1,i) , rep( "darkgray" ,length(l)-i) ) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment