set.seed(123)
# Data preparation
# +++++++++++++++
data("iris")
head(iris)
# Remove species column (5) and scale the data
iris.scaled <- scale(iris[, -5])
# K-means clustering
# +++++++++++++++++++++
km.res <- kmeans(iris.scaled, 3, nstart = 25)
# Visualize kmeans clustering
# use repel = TRUE to avoid overplotting
fviz_cluster(km.res, iris[, -5], frame.type = "norm")
# Change the color and theme
fviz_cluster(km.res, iris[, -5]) +
scale_color_brewer(palette = "Set2")+
scale_fill_brewer(palette = "Set2") +
theme_minimal()
## Not run:
# # Show points only
# fviz_cluster(km.res, iris[, -5], geom = "point")
# # Show text only
# fviz_cluster(km.res, iris[, -5], geom = "text")
#
# # PAM clustering
# # ++++++++++++++++++++
# require(cluster)
# pam.res <- pam(iris.scaled, 3)
# # Visualize pam clustering
# fviz_cluster(pam.res, geom = "point", frame.type = "norm")
# ## End(Not run)
# Hierarchical clustering
# ++++++++++++++++++++++++
# Use hcut() which compute hclust and cut the tree
hc.cut <- hcut(iris.scaled, k = 3, hc_method = "complete")
# Visualize dendrogram
fviz_dend(hc.cut, show_labels = FALSE, rect = TRUE)
# Visualize cluster
fviz_cluster(hc.cut, frame.type = "convex")
Run the code above in your browser using DataLab