# Normal prior.posterior

x <- 4
phi <- 2
theta_0 <- 0
phi_0 <- 2

theta_range <- seq(-5, 5, length.out = 1000)

# Note dnorm calculates PDF of normal at given point

prior <- dnorm(theta_range, mean = theta_0, sd = sqrt(phi_0))
likelihood <- dnorm(theta_range, mean = x, sd = sqrt(phi))
post_mean <- (x* 1/phi + theta_0 * 1/phi_0)/(1/phi + 1/phi_0)
post_var <- 1 / (1/phi + 1/phi_0)

posterior <- dnorm(theta_range, mean = post_mean, sd = sqrt(post_var))

# increase margins 

par(mar = c(5, 5, 2, 2) + 0.1)

# Plot

plot(theta_range, prior, type = "l", col = "blue", xlab = "θ", ylab = "Probability Density",
     main = "Prior, Likelihood, Posterior Dists")

lines(theta_range, likelihood, col = "green")
lines(theta_range, posterior, col = "red")
legend("topleft", legend = c("Prior", "Likelihood", "Posterior"), 
       col = c("blue", "green", "red"), lty = 1, cex = 0.7)