如何在同一幅画多个轮廓

时间:2018-07-19 08:59:53

标签: r ggplot2

我正在尝试使用R中的ggplot2在同一图中获得两个轮廓。

以下是可重现的示例:

library(MASS)
library(ggplot2)
# first contour
m <- c(.0, -.0)
sigma <- matrix(c(1,.5,.5,1), nrow=2)
data.grid <- expand.grid(s.1 = seq(-3, 3, length.out=200), s.2 = seq(-3, 3, length.out=200))
q.samp <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m, sigma = sigma))

plot1 <- ggplot(q.samp, aes(x = s.1, y = s.2, z = prob)) +
  stat_contour(color = 'green')

# second contour
m1 <- c(1, 1)
sigma1 <- matrix(c(1,-.5,-.5,1), nrow=2)
set.seed(10)
data.grid1 <- expand.grid(s.1 = seq(-3, 3, length.out=200), s.2 = seq(-3, 3, length.out=200))
q.samp1 <- cbind(data.grid1, prob = mvtnorm::dmvnorm(data.grid1, mean = m1, sigma = sigma1))
plot2 <- ggplot(q.samp1, aes(x = s.1, y = s.2, z = prob)) +
  stat_contour(color = 'red')

但是,尝试plot1 + plot2也不起作用。有没有一种方法可以在同一图上获得两个轮廓。

1 个答案:

答案 0 :(得分:0)

包括另一个具有不同数据的stat_contour怎么办?

ggplot(q.samp1, aes(x = s.1, y = s.2, z = prob)) +
  stat_contour(color = 'red') + 
  stat_contour(data = q.samp, aes(x = s.1, y = s.2, z = prob), color = 'green')

enter image description here