Last active
December 17, 2015 21:39
-
-
Save dmarcelinobr/5676298 to your computer and use it in GitHub Desktop.
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
# Simulate randomly-distributed data | |
nObs <- 5000 | |
myData <- data.frame(X = rnorm(nObs), Y = rnorm(nObs)) | |
nClusters <- 7 # Cluster it | |
kMeans <- kmeans(myData, centers = nClusters) | |
myData$Cluster <- as.factor(kMeans$cluster) | |
# Plot points colored by cluster | |
p1 <- ggplot(myData, | |
aes(x = X, y = Y, colour = Cluster)) | |
p1 <- p1 + geom_point() | |
print(p1) | |
# Illustration of stat_density2d, encoding density into alpha | |
p2 <- ggplot(myData, | |
aes(x = X, y = Y)) | |
p2 <- p2 + stat_density2d(aes(fill = Cluster, colour = Cluster, | |
alpha = ..level..), | |
geom = "polygon") | |
p2 <- p2 + scale_alpha(range = c(0, 1/2), guide = "none") # Narrow alpha range | |
p2 <- p2 + coord_equal() | |
print(p2) | |
# Illustration of stat_density2d, encoding density into linewidth | |
p3 <- ggplot(myData, | |
aes(x = X, y = Y)) | |
p3 <- p3 + stat_density2d(aes(colour = Cluster, | |
size = ..level..), | |
fill = "transparent", | |
geom = "polygon") | |
p3 <- p3 + scale_size(range = c(0, 2), guide = "none") # Narrow size/linewidth range | |
p3 <- p3 + coord_equal() | |
print(p3) | |
# Combination of both | |
p4 <- ggplot(myData, | |
aes(x = X, y = Y)) | |
p4 <- p4 + stat_density2d(aes(fill = Cluster, colour = Cluster, | |
alpha = ..level.., | |
size = ..level..), | |
geom = "polygon") | |
p4 <- p4 + scale_alpha(range = c(0, 1/2), guide = "none") # Narrow alpha range | |
p4 <- p4 + scale_size(range = c(0, 3/2), guide = "none") # Narrow size/linewidth range | |
p4 <- p4 + coord_equal() | |
print(p4) | |
ggsave("stat_density2d.jpeg", p4, width=5.5, height=5.5, dpi=600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment