Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created October 7, 2011 18:58
Show Gist options
  • Save dsparks/1271087 to your computer and use it in GitHub Desktop.
Save dsparks/1271087 to your computer and use it in GitHub Desktop.
Neat two-dimensional density plots
library(ggplot2)
x.centers <- c(-2, 1, 3)
x.ses <- c(1, 2, 1/2)
y.centers <- c(1/2, -2, 2)
y.ses <- c(1/4, 3/2, 1)
NN <- 5000#0
Sample1 <- cbind(rnorm(NN, x.centers[1], x.ses[1]), rnorm(NN, y.centers[1], y.ses[1]))
Sample2 <- cbind(rnorm(NN, x.centers[2], x.ses[2]), rnorm(NN, y.centers[2], y.ses[2]))
Sample3 <- cbind(rnorm(NN, x.centers[3], x.ses[3]), rnorm(NN, y.centers[3], y.ses[3]))
PlotFrame <- data.frame(cbind(rep(c("G1", "G2", "G3"), each = NN), rbind(Sample1, Sample2, Sample3)))
colnames(PlotFrame) <- c("LABELS", "X", "Y")
PlotFrame[, 2:3] <- apply(PlotFrame[, 2:3], 2, as.numeric)
Plot1 <- ggplot(data = PlotFrame, aes(x = X, y = Y, colour = LABELS))
Plot1 <- Plot1 + geom_density2d()
print(Plot1)
Plot2 <- ggplot(data = PlotFrame, aes(x = X, y = Y, group = LABELS))
Plot2 <- Plot2 + stat_density2d(aes(colour = ..level..), fill = "transparent", geom="polygon")
print(Plot2)
Plot3 <- ggplot(data = PlotFrame, aes(x = X, y = Y, group = LABELS))
Plot3 <- Plot3 + stat_density2d(aes(fill = LABELS, colour = LABELS, alpha = ..level..), geom="polygon")
print(Plot3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment