I'm trying to create an illustration of a bivariate joint and conditional probability distribution using a contour plot in ggplot2
. What I'm trying to recreate is a subset of features of the following image from this site:
(I'm only interested in joint and conditional probabilities, not marginal.) My main issue here is overlaying Gaussians for $y$ given $x=x_0$, as shown in the image. This would require specifying the conditional distributions for $y$ given $x=x_0$ and somehow plotting it on an existing contour plot. So far I couldn't properly generate the line for $x = x_0$, since it does not stretch across the entire y axis.
This is the image generated by my code. You can find the code below the image.
library(MASS)
library(ggplot2)
n <-1e5
x <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2))
#x <- mvrnorm(n, mu=c(0,0), Sigma=matrix(c(0.8,1,0.8,1), ncol=2))
df = data.frame(x); colnames(df) = c("x","y")
min.x = min(df$x)
max.x = max(df$x)
min.y = min(df$y)
max.y = max(df$y)
commonTheme = list(labs(color="Density",fill="Density",
x="x",
y="y"),
theme_bw(),
theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
legend.position='none'))
ggplot(data=df,aes(x,y)) +
stat_density2d(aes(fill=..level..,alpha=..level..), geom='polygon', colour='black') +
scale_fill_continuous(low="yellow", high="red") +
guides(alpha="none") +
geom_line(data=data.frame(x=0.4*max(df$x), y=min(df$y):max(df$y)), size=1.0, colour = "blue")+
geom_point(data=data.frame(x=0.4*max(df$x), y=0.41*max(df$y)), colour="blue", size=3) +
#scale_x_continuous(limits = c(min.x, max.x)) +
#scale_y_continuous(limits = c(min.y, max.y)) +
commonTheme
Any advice?