Skip to content

Instantly share code, notes, and snippets.

@dmarcelinobr
Last active December 17, 2015 21:39
Show Gist options
  • Save dmarcelinobr/5676298 to your computer and use it in GitHub Desktop.
Save dmarcelinobr/5676298 to your computer and use it in GitHub Desktop.
# 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