user24318
user24318

Reputation: 485

Overlay two contours of bivariate gaussian distribution using ggplot2

I want to overlay two contours of bivariate guassian distribution on the same plot using ggplot2 using different color for each contour. I looked at a previous post about how to plot contours of bivariate gaussian (Plot multivariate Gaussian contours with ggplot2). But that is only plotting one contour. I tried using stat_density2d, but was unsuccessful. Here is my code with reproducible example.

set.seed(13)
m1 <- c(.5, -.5)
sigma1 <- matrix(c(1,.5,.5,1), nrow=2)

m2 <- c(0, 0)
sigma2 <- matrix(c(140,67,67,42), nrow=2)


data.grid <- expand.grid(s.1 = seq(-25, 25, length.out=200), s.2 = seq(-25, 
25, length.out=200))
q.samp <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m2, 
sigma = sigma2))
ggplot(q.samp, aes(x=s.1, y=s.2, z=prob)) + 
    geom_contour() +
    coord_fixed(xlim = c(-25, 25), ylim = c(-25, 25), ratio = 1) 

Upvotes: 2

Views: 1385

Answers (2)

Roman Luštrik
Roman Luštrik

Reputation: 70653

Another option would be to combine the data into one data.frame and map color to the "origin" of where the data came from. This gives you a handy legend, should you need one, and all its benefits (like mapping color).

q1.samp = cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m1, sigma=sigma1))
q1.samp$origin <- "q1"
q2.samp = cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m2, sigma=sigma2))
q2.samp$origin <- "q2"

q <- rbind(q1.samp, q2.samp)

ggplot(q, aes(x=s.1, y=s.2, z=prob, color = origin)) + 
  geom_contour() +
  coord_fixed(xlim = c(-25, 25), ylim = c(-25, 25), ratio = 1) 

enter image description here

Upvotes: 3

Spacedman
Spacedman

Reputation: 94277

If I follow your code and create q1.samp and q2.sampfrom your parameters:

 q2.samp = cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m2, sigma=sigma2))
 q1.samp = cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m1, sigma=sigma1))

then I can do this:

 ggplot() + 
  geom_contour(data=q1.samp,aes(x=s.1,y=s.2,z=prob)) +    
  geom_contour(data=q2.samp,aes(x=s.1,y=s.2,z=prob),col="red")

then I get one set of contours in the default colour and one in red.

enter image description here

Upvotes: 4

Related Questions