#Gibbs sampler for bivariate normal 
library(MASS)
mu = c(0,0)
Sigma = matrix(c(1,0.0,0.0,1),ncol=2)
x = c(-2.5,2.5)
S = 5000
x.sim = matrix(nrow=2*S,ncol=2)
x.sim[1,] = x
sig1 = sqrt(Sigma[1,1]-Sigma[1,2]*Sigma[2,1]/Sigma[2,2])
sig2 = sqrt(Sigma[2,2]-Sigma[2,1]*Sigma[1,2]/Sigma[1,1])
x[2] = rnorm(1,mu[2]+Sigma[2,1]*(x[1]-mu[1])/Sigma[1,1],sig2)
x.sim[2,] = x
for(i in 2:S)
{
  x[1] = rnorm(1,mu[1]+Sigma[1,2]*(x[2]-mu[2])/Sigma[2,2],sig1)
  x.sim[2*i-1,] = x
  x[2] = rnorm(1,mu[2]+Sigma[2,1]*(x[1]-mu[1])/Sigma[1,1],sig2)
  x.sim[2*i,] = x
}
x.sim = data.frame(x1=x.sim[,1],x2=x.sim[,2])
library(ggplot2)

#Make ellipse with 95% CI
r = qchisq(0.75,2)/2
theta=seq(0,2*pi,length=100)
x.el = r*cbind(cos(theta),sin(theta))
Sig.chol = chol(Sigma)
x.el = matrix(rep(mu,100),ncol=2,byrow=T)+x.el%*%Sig.chol
x.el = data.frame(X1=x.el[,1],X2=x.el[,2])
dft <- data.frame(mvrnorm(100000, c(0, 0), Sigma))

#x.sim$x1l = x.sim$x1[c(1,1:(S-1))]
#x.sim$x2l = x.sim$x2[c(1,1:(S-1))]

labs1 <- c('Draws', 'Steps of the sampler', '90% HPD')
p1 <- ggplot() +
  geom_point(data = x.sim, aes(x = x1,color = '1',
                              y = x2)) +
  geom_line(data = x.sim, aes(x = x1,color = '2',
                                 y = x2)) +
  stat_ellipse(data = x.el, aes(x = X1, y = X2, color = '3'), level = 0.9) +
  coord_cartesian(xlim = c(-3.5, 3), ylim = c(-3.5, 3)) +
  labs(x =expression(theta[1]), y =expression(theta[2])) 
show(p1)

