Guest User

Untitled

a guest
Jan 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. # ----------------------------------------------------
  2. # Create animation for visualising likelihood function
  3. # ----------------------------------------------------
  4.  
  5. # Create a working directory for this file
  6. # Add an images folder
  7. # Run script
  8. # Create GIF using Photoshop
  9.  
  10. # Set binomial distribution parameters
  11. n = 10 # Sample size
  12. k = 0:n # Discrete probability space
  13. k.heads = 2 # Number of heads thrown
  14.  
  15. # Set theta range and interval
  16. thetas = seq(0, 1, .01)
  17. thetas = c(thetas, rev(thetas[c(-1,-length(thetas))]))
  18.  
  19. # Set bar colors
  20. col = rep("beige", n+1) # all bars beige
  21. col[k.heads+1] = 'cyan' # Data to cyan
  22.  
  23. # First manually create images folder. Write files to images folder.
  24. png(file="images/binomial_likelihood_function%02d.png", width=800, height=300)
  25.  
  26. for(theta in thetas) {
  27.  
  28. # Set layout for two plots
  29. layout(matrix(1:2, 1, 2))
  30.  
  31. # Plot binomial distribution
  32. title = bquote('Binomial distribution for' ~ theta ~ '=' ~ .(theta))
  33.  
  34. barplot( dbinom(k, n, theta),
  35. main = title,
  36. names.arg = 0:10,
  37. xlab = "number of head",
  38. ylab = "P(head)",
  39. beside = TRUE,
  40. col = col,
  41. las = 1,
  42. ylim = c(0,1)
  43. )
  44.  
  45. # Plot Likelihood function
  46. plot( thetas, dbinom(k.heads, n,thetas),
  47. type = 'l',
  48. lwd = 3,
  49. xlim = c(0,1),
  50. main = bquote("Likelihood function for" ~ .(k.heads)~ "/" ~.(n) ~ "heads"),
  51. ylab = expression(paste('Likelihood - ', "P(D|", theta, ")" )),
  52. xlab = expression(theta),
  53. ylim = c(0,1),
  54. las = 1
  55. )
  56.  
  57. # Plot likelihood dot on likelihood function
  58. points(theta, dbinom(k.heads, n, theta),
  59. cex = 2,
  60. pch = 21,
  61. bg = "cyan")
  62.  
  63. # Add tracking line
  64. lines(c(theta,theta), c(0,dbinom(k.heads, n, theta)), lty='dashed')
  65.  
  66. }
  67.  
  68. dev.off()
Add Comment
Please, Sign In to add comment