R语言 一个图形中的等高线图

zdwk9cvp  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(192)
mu1 <- c(0,0)
mu2<-c(2*sqrt(2),2*sqrt(2))
sigma1 <- matrix(c(2,0,.0,2), nrow=2)
sigma2<-matrix(c(2, 1.2, 1.2, 2),ncol = 2)
data.grid <- expand.grid(s.1 = seq(-6, 10, length.out=100), s.2 = seq(-6, 10, length.out=100))
q.samp1 <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = mu1, sigma = sigma1))
q.samp2 <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid1, mean = mu2, sigma =sigma2))

我的代码如下:

ggplot(q.samp1, aes(x = s.1, y = s.2, z = prob)) +
  stat_contour(color = 'red',bins = 12 ) + 
  stat_contour(data = q.samp2, aes(x = s.1, y = s.2, z = prob), color = 'green',bins = 12,binwidth = 1)+geom_point(aes(x = 0, y =0))+
  geom_point(aes(x=2*sqrt(2),y=2*sqrt(2)))+xlab("Random slop")+ylab("Random intercept")

我想在R中绘制上述数据的轮廓,如下图,请帮助我

kt06eoxx

kt06eoxx1#

library(ggplot2)
library(mvtnorm)

mu1 <- c(0, 0)
mu2 <- c(2 * sqrt(2), 2 * sqrt(2))
sigma1 <- matrix(c(2, 0, 0, 2), nrow = 2)
sigma2 <- matrix(c(2, 1.2, 1.2, 2), ncol = 2)

data.grid <- expand.grid(s.1 = seq(-6, 10, length.out = 100), s.2 = seq(-6, 10, length.out = 100))

q.samp1 <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = mu1, sigma = sigma1))
q.samp2 <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = mu2, sigma = sigma2))

ggplot() +
  geom_contour(data = q.samp1, aes(x = s.1, y = s.2, z = prob), color = 'red', bins = 12) +
  geom_contour(data = q.samp2, aes(x = s.1, y = s.2, z = prob), color = 'green', bins = 12) +
  geom_point(aes(x = 0, y = 0)) +
  geom_point(aes(x = 2 * sqrt(2), y = 2 * sqrt(2))) +
  xlab("Random slop") +
  ylab("Random intercept")

在此更新的代码中:
我删除了stat_contour函数,并将其替换为geom_contour。每个等高线图的颜色美感直接在geom_contour中设置。geom_point函数用于添加坐标(0,0)和(2 * sqrt(2),2 * sqrt(2))处的蓝点。x轴和y轴标签分别使用xlab和ylab函数设置。请注意,生成的图可能不是您提到的图像的精确副本,因为轮廓的外观可能会因数据和比例而异。但是,此代码应该根据提供的数据给予等高线图。

相关问题