如何修改R代码来生成这样的等高线图?

b4wnujal  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(199)
library(MASS)
library(ggplot2)
# first contour
m <- c(0,0)
n<-c(2*sqrt(2),2*sqrt(2))
sigma <- matrix(c(2,0,.0,2), nrow=2)
data.grid <- expand.grid(s.1 = seq(-6, 10, length.out=100), s.2 = seq(-6, 10, length.out=100))
q.samp <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m, sigma = sigma))
ggplot(q.samp, 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')

#sigma1 <- matrix(c(1,-.5,-.5,1), nrow=2)
set.seed(10)
data.grid1 <- expand.grid(s.1 = seq(-6, 40, length.out=200), s.2 = seq(-6, 40, length.out=200))
q.samp1 <- cbind(data.grid1, prob = mvtnorm::dmvnorm(data.grid1, mean = n, sigma = matrix(c(2, 1.2, 1.2, 2), nrow = 2)))
ggplot(q.samp1, aes(x = s.1, y = s.2, z = prob)) +
  stat_contour(color = 'red',bins = 12 ) + 
  stat_contour(data = q.samp, 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")

我想绘制等高线图,我得到了上面的图,但我想像下面的图像绘制

ctehm74n

ctehm74n1#

我不确定这是否完美,但它应该让你开始。基本上你需要ggforce::geom_ellipseggplot2::geom_segment

library(ggforce); library(ggplot2)
ggplot() +
       geom_ellipse(aes(x0 = 0, y0 = 0, a = 3, b = 3, angle = 0), colour = "green") +
       geom_ellipse(aes(x0 = 2*sqrt(2), y0 = 2*sqrt(2), a = 4, b = 3, angle = pi/4), 
             colour = "purple") +
       coord_fixed() +
       theme_classic() +
       annotate(geom = "segment", x = 0, y = 0, xend = 2*sqrt(2), yend = 2*sqrt(2))

相关问题