Skip to content

Instantly share code, notes, and snippets.

@JimGrange
Created November 17, 2016 13:16
Show Gist options
  • Save JimGrange/006ad5778a17187b488cca27817638fc to your computer and use it in GitHub Desktop.
Save JimGrange/006ad5778a17187b488cca27817638fc to your computer and use it in GitHub Desktop.
setwd("C:/Users/psa33/Dropbox/Work/Blog/gifs/increasingN")
binWidth <- 0.005
# define parameter space
x <- seq(from = binWidth / 2, to = 1 - binWidth / 2, by = binWidth)
# what rate of fairness is the coin?
rate <- 0.5
# how many flips to go up to?
n <- 100
# declare the prior
prior <- c(9, 1)
priorDensity <- dbeta(x, prior[1], prior[2])
# get a matrix to store all data likelihoods & posteriors
likelihood <- matrix(0, nrow = length(x), ncol = n)
posterior <- matrix(0, nrow = length(x), ncol = n)
for(i in 1:n){
likelihood[, i] <- dbeta(x, 1 + i * rate, 1 + i * rate)
posterior[, i] <- dbeta(x, prior[1] + i * rate, prior[2] + i * rate)
}
# loop over number of heads 1 to n and store a plot (in png) for each step
for(i in 1:n){
# set up the file
currFile <- paste(getwd(), "/plot_", i, ".png", sep = "")
# initiate the png file
png(file = currFile, width = 1200, height = 1000, res = 200)
# initiat
# do the plot
plot(x, posterior[, i], type = "l",
ylim = c(0, max(c(likelihood, posterior, priorDensity))), lty = 1,
lwd = 3, col = "skyblue", xlab = bquote(theta), ylab = "Density",
las = 1, main = paste("Number of Flips = ", i, sep = ""))
lines(x, likelihood[, i], type = "l", lty = 2, col = "red")
lines(x, priorDensity, type = "l", lty = 2, col = "gray48")
legend("topleft", c("Prior", "Likelihood", "Posterior"), lty = c(2, 2, 1),
col = c("gray48", "red", "skyblue"), lwd = c(1, 1, 4), bty = "n")
dev.off()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment