如何在ggplot中添加集群边界以进行自组织映射?

时间:2019-04-09 02:31:31

标签: r ggplot2 cluster-analysis self-organizing-maps

我正在使用此链接中的代码:http://blog.schochastics.net/post/soms-and-ggplot/在R中绘制我的自组织映射。但是,我需要一些类似于内置函数add.cluster.boundaries的功能。请帮忙。

library(tidyverse)  # for data wrangling
library(stringr)    # for string manipulations
library(kohonen)    # implements self organizing maps
library(ggforce)    # for additional ggplot features

r_sample <- sample(1:nrow(fifa_tbl),2000)
fifa_tbl <- fifa_tbl[r_sample,]
glimpse(fifa_tbl)

fifa_som <- fifa_tbl %>%
  select(Acceleration:Volleys) %>%
  scale() %>%
  som(grid = somgrid(15, 15, "hexagonal","gaussian"), rlen = 800)

som_grid <- fifa_som[[4]]$pts %>%
  as_tibble %>% 
  mutate(id=row_number())
som_grid

som_pts <- tibble(id = fifa_som[[2]],
                  dist = fifa_som[[3]],
                  type = fifa_tbl$position2)

som_pts <- som_pts %>% left_join(som_grid,by="id")

p <- som_grid %>% 
  ggplot(aes(x0=x,y0=y))+
  geom_circle(aes(r=0.5))+
  theme(panel.background = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        legend.position = "bottom")

p+geom_jitter(data=som_pts,aes(x,y,col=type),alpha=0.5)+
  scale_color_manual(values=c("#F8766D","#7CAE00","#00B0B5","#C77CFF"),name="Position")

上面的代码就是这样的。 enter image description here

但是,我希望使用ggplot添加群集边界。软件包kohonen具有一个内置函数add.cluster.boundaries来实现。

som.cluster <- cutree(hclust(dist(as.data.frame(fifa_som$codes)), method = "complete"), 6)

plot(fifa_som, type="mapping", pch=20,
     col = c("#F8766D","#7CAE00","#00B0B5","#C77CFF")[as.integer(fifa_tbl$position2)],
     shape = "round")

add.cluster.boundaries(fifa_som, som.cluster, lwd = 3, lty = 2)

我想在上一个代码块中使用ggplot生成此类簇边界。

0 个答案:

没有答案