首页 > 解决方案 > 使用 facetwrap 的多个 Kmeans 聚类和绘图

问题描述

我想问一下如何为同一数据集自动化多个 K-means 聚类 - 我想在聚类数量发生变化时创建多个 kmean 聚类,然后使用绘制结果facet_wrap

因此,人们可以观察一下似乎最合适的簇数。

我可以这样做,因为代码非常手动 - 它可以以某种方式自动化:


library(tidyverse)
Y <- mtcars %>% select(hp, disp)

kme1 <- kmeans(Y, 3)
kme2 <- kmeans(Y, 4)
kme3 <- kmeans(Y, 5)
kme4 <- kmeans(Y, 6)

A <- broom::augment(kme1, Y) %>% 
  mutate(num_clust = 3)
B <- broom::augment(kme2, Y) %>% 
  mutate(num_clust = 4)
C <- broom::augment(kme3, Y) %>% 
  mutate(num_clust = 5)
D <- broom::augment(kme4, Y) %>% 
  mutate(num_clust = 6)

rbind(A, B, C, D) %>% 
  ggplot(aes(hp, disp)) + 
  geom_point(aes(color = .cluster)) + 
  stat_ellipse(aes(x=hp,y=disp,fill=factor(.cluster)),
               geom="polygon", level=0.95, alpha=0.2) + 
  facet_wrap(~num_clust)

标签: rggplot2k-means

解决方案


您可以使用purrr::map和变体:

library(tidyverse)
Y <- mtcars %>% select(hp, disp)

map(set_names(3:6), ~kmeans(Y, .x)) %>% 
  map(broom::augment, Y) %>% 
  imap(~mutate(.x, num_clust = .y)) %>% 
  bind_rows() %>% 
  ggplot(aes(hp, disp)) + 
  geom_point(aes(color = .cluster)) + 
  stat_ellipse(aes(x=hp,y=disp,fill=factor(.cluster)),
               geom="polygon", level=0.95, alpha=0.2) + 
  facet_wrap(~num_clust)

推荐阅读