forked from avehtari/BDA_R_demos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo2_1.jmd
62 lines (51 loc) · 2.01 KB
/
demo2_1.jmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---
title: "Bayesian data analysis demo 2.1"
author: "Aki Vehtari, Markus Paasiniemi, Arthur Newbury"
output:
html_document:
theme: readable
code_download: true
---
## Probability of a girl birth given placenta previa (BDA3 p. 37).
437 girls and 543 boys have been observed. Calculate and plot the
posterior distribution of the proportion of girls $\theta$, using
uniform prior on $\theta$.
Statsplots.jl is used for plotting
to install new packages, type e.g. ] add SatsPlots
```julia term = false
using CairoMakie, Distributions, DataFrames
set_theme!(theme_minimal(),Axis = (leftspinevisible = false,yticklabelsvisible=false,),)
```
Posterior is Beta(438,544)
```julia term = false
# evenly spaced values can be produced by the syntax start:step:stop
df1 = DataFrame( θ = 0.375:0.001:0.525)
α,β = 438,544
posterior = Beta(α,β)
# the pdf function 'knows' when it is supplied a Beta distribution
df1.p =pdf.(posterior,df1.θ);
```
compute also 95% central interval
```julia term = false
# LinRange creates evenly spaced values from 2.5% quantile
# to 97.5% quantile (i.e., 95% central interval)
# The '...' notation tells Julia to unpack the output from the quantile function
df2 =DataFrame(θ = LinRange(quantile(posterior,[0.025,0.975])..., 100))# compute the posterior density
df2.p =pdf.(posterior,df2.θ);
```
Plot posterior (Beta(438,544))
and 48.8% line for population average
```julia out_width = "70%"
fig, ax, post = lines(df1.θ, df1.p, color = :black, linewidth = 4,
axis = (title = "Posterior distribution given uniform prior",
titlesize = 24,))
# Add a layer of colorized 95% posterior interval
i95 = band!(df2.θ,fill(0.0,length(df2.p)), df2.p, color = (:blue,0.2))
# Add the proportion of girl babies in general population
pop = vlines!(ax, [0.488], color = :black, linestyle=:dash)
# Decorate the plot a little
Legend(fig[2,1], [post, i95, pop], ["Poseterior density = Beta($(α),$(β))",
"95% posterior interval", "population average"],
orientation = :horizontal,tellwidth = false, tellheight = true)
fig
```