Created
December 3, 2018 15:50
-
-
Save jake-westfall/4c2149152a04fa65cc74879b3af161f8 to your computer and use it in GitHub Desktop.
Illustration of the concept of conditioning on a random variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("scatterplot3d") | |
library("MASS") | |
path <- "/Users/jakewestfall/Desktop/" | |
# simulate data from gaussian copula | |
covmat <- matrix(.9, nrow=3, ncol=3) | |
diag(covmat) <- 1 | |
dat <- pnorm(mvrnorm(n=3000, mu=c(0,0,0), Sigma=covmat)) | |
# pairs(dat) | |
# set up the plot params | |
png(paste0(path, "3d.png"), height=8, width=16, | |
units="in", res=200, pointsize=20) | |
layout(cbind(1,2)) | |
# scatterplot3d ----------------------------------------------------------- | |
# draw the points under the plane | |
s3d <- scatterplot3d( | |
dat[dat[,3] < .8,], pch=20, color=rgb(0, 0, 0, .4), | |
xlim=0:1, ylim=0:1, zlim=0:1, | |
xlab="X", ylab="", zlab="Y", | |
main="Draws from joint distribution\nP(X, Y, Z)" | |
) | |
# draw the plane | |
s3d$plane3d( | |
Intercept = .8, x.coef = 0, y.coef = 0, | |
lty = 1, lwd = 0.25, draw_polygon = TRUE, draw_lines = FALSE, | |
polygon_args = list(col = scales::alpha("cornsilk2", 0.5), lty = 1, lwd = 0.5) | |
) | |
# draw the points above the plane | |
s3d$points3d(dat[dat[,3] > .8,], pch=20, col=rgb(0, 0, 0, .4)) | |
# Add rotated axis label | |
p2 <- s3d$xyz.convert(x = 1.3, y = .2, z = 0) | |
text(p2$x, p2$y, "Z", adj = 0.5, srt = 40, xpd = TRUE) | |
# 2D ---------------------------------------------------------------------- | |
# scatterplot3d messes with the margins, so set them back... | |
par(mar=c(5,4,4,2)) | |
# simulate even more data from the same copula | |
bigdat = pnorm(mvrnorm(n=1000000, mu=c(0,0,0), Sigma=covmat)) | |
# empty plot | |
plot(x=0:1, y=0:1, cex=0, mgp=2:0, ylab="Z", xlab="X", | |
main="Draws from conditional distribution\nP(X, Z | Y = 0.8)") | |
# background color | |
rect(xleft=-1, xright=2, ybottom=-1, ytop=2, col=scales::alpha("cornsilk2", 0.5)) | |
# add the points | |
points(x=bigdat[abs(bigdat[,1] - .8) < .0005, 2], | |
y=bigdat[abs(bigdat[,1] - .8) < .0005, 3], | |
pch=19, col=rgb(0, 0, 0, .4)) | |
dev.off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment