Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

plot - How to draw a small bivariate distribution in R?

For illustrative purposes, I am trying to draw a small bivariate normal distribution. I would like it to be tight, centered at (3,4;1), and with a radius of 0.5 or less. By that, I mean that I would like the datapoints to be confined within a small radius.

Below see the code I am using (from this website); I have tried to tweak it in different ways, but the bivariate is always spread out.

library(MASS)
N <- 200 # Number of random samples
set.seed(123)
# Parameters 
rho <- 0.5
mu1 <- 3.4; s1 <- 1
mu2 <- 1; s2 <- 1

# Parameters for bivariate normal distribution
mu <- c(mu1,mu2) # Mean 
sigma <- matrix(c(s1^2, s1*s2*rho, s1*s2*rho, s2^2),
                2) # Covariance matrix
X <- mvrnorm(N, mu = mu, Sigma = sigma)
z <- kde2d(X[,1], X[,2], n=50)

plot(X, xlab="X label", ylab="Y label", 
    xlim=c(2,6), ylim=c(-1,3.5),pch=19, cex=.4)
contour(z, drawlabels=FALSE, add=TRUE)

Created on 2021-01-05 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using s2 <- s1 <- 0.25 solves the problem as pointed out by @user20650.

library(MASS)
N <- 200 # Number of random samples
set.seed(123)
# Parameters 
rho <- 0.5
mu1 <- 3.4; s1 <- 0.25
mu2 <- 1; s2 <- 0.25

# Parameters for bivariate normal distribution
mu <- c(mu1,mu2) # Mean 
sigma <- matrix(c(s1^2, s1*s2*rho, s1*s2*rho, s2^2),
                2) # Covariance matrix
X <- mvrnorm(N, mu = mu, Sigma = sigma)
z <- kde2d(X[,1], X[,2], n=50)

plot(X, xlab="X label", ylab="Y label", 
    xlim=c(2,6), ylim=c(-1,3.5),pch=19, cex=.4)
contour(z, drawlabels=FALSE, add=TRUE)

Created on 2021-01-05 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...