如何用扩展椭圆绘制二元正态分布图

时间:2014-09-08 06:16:33

标签: r

如何绘制具有扩展椭圆的二元正态分布并添加5%,25%,50%,75%和 情节中95%的标签?谢谢!

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用名为 mvtnorm 的R包创建等高线图。

让我们假设您正在尝试绘制一个二元正态分布,其中mu_x = 1且mu_y = 1且方差矩阵为c(2,1,1,1)。为x,y,z生成100个观测值。您可以为此方案创建等高线图:

library(mvtnorm)
x.points <- seq(-3,3,length.out=100)
y.points <- x.points
z <- matrix(0,nrow=100,ncol=100)
mu <- c(1,1)
sigma <- matrix(c(2,1,1,1),nrow=2)
for (i in 1:100) {
   for (j in 1:100) {
    z[i,j] <- dmvnorm(c(x.points[i],y.points[j]),
    mean=mu,sigma=sigma)
   }
}
contour(x.points,y.points,z)

答案 1 :(得分:1)

这是一种在所需水平上计算轮廓的解决方案

#####
# Compute points and rotation matrix

# input
theta <- c(1, 2)
sigma <- diag(c(3^2, 2^2))
sigma[2, 1] <- sigma[1, 2] <- sqrt(sigma[1, 1] * sigma[2, 2]) * .5 

# we start from points on the unit circle
n_points <- 100
xy <- cbind(sin(seq(0, 2 * pi, length.out = n_points)), 
            cos(seq(0, 2 * pi, length.out = n_points)))

# then we scale the dimensions
ev <- eigen(sigma)
xy[, 1] <- xy[, 1] * 1 
xy[, 2] <- xy[, 2] * sqrt(min(ev$values) / max(ev$values))

# then rotate
phi <- atan(ev$vectors[2, 1] / ev$vectors[1, 1])
R <- matrix(c(cos(phi), sin(phi), -sin(phi), cos(phi)), 2) 
xy <- tcrossprod(R, xy)

# the quantiles you ask for
chi_vals <- qchisq(c(.05, .25, .50, .75, .95), df = 2) * max(ev$values)

#####
# Plot contours
par(mar = c(4.5, 4, .5, .5))
plot(c(-8, 10), c(-4, 8), type = "n", xlab = "x", ylab = "y")
for(r in sqrt(chi_vals))
  lines(r * xy[1, ] + theta[1], r * xy[2, ] + theta[2], lty = 1)

enter image description here