Created
May 4, 2015 17:55
-
-
Save TysonStanley/45659b88ec7a0a568dea to your computer and use it in GitHub Desktop.
Two Dimensional Density and Hexbin Plots with Simulated Data (ggplot2 & hexbin)
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
# Simulating Correlated Data | |
# (this is a variant of something I found online but I can't find out who posted it...) | |
n <- 2000 # length | |
rho <- 0.6 # desired correlation = cos(angle) | |
theta <- acos(rho) # corresponding angle | |
pred <- rnorm(n, 1, 1) # predictor vector | |
x2 <- rnorm(n, 2, 0.5) # new random data for response vector | |
X <- cbind(pred, x2) # matrix of pred and x2 | |
Xctr <- scale(X, center=TRUE, scale=FALSE) # centered columns (mean 0) | |
Id <- diag(n) # an identity matrix | |
Q <- qr.Q(qr(Xctr[ , 1, drop=FALSE])) # QR-decomposition | |
P <- tcrossprod(Q) # = Q Q' # projection onto space defined by pred | |
x2o <- (Id-P) %*% Xctr[ , 2] # x2ctr made orthogonal to x1ctr | |
Xc2 <- cbind(Xctr[ , 1], x2o) # bind to matrix | |
Y <- Xc2 %*% diag(1/sqrt(colSums(Xc2^2))) # scale columns to length 1 | |
resp <- Y[ , 2] + (1 / tan(theta)) * Y[ , 1] # final response vector | |
data <- data.frame(pred,resp) | |
# 2 Dimensional Plots | |
library(ggplot2) | |
# Density Plot | |
Plot <- ggplot(data,aes(x=pred,y=resp)) + | |
stat_density2d(aes(colour=..level..,fill=..level..,),alpha=.35, geom="polygon") | |
Plot | |
library(hexbin) | |
# Hexbin Plot | |
Plot2 <- ggplot(data, aes(x=pred, y=resp)) + | |
stat_binhex() | |
Plot2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment