美文网首页
ggplot-geom_point 聚类散点图添加簇标签

ggplot-geom_point 聚类散点图添加簇标签

作者: 倪桦 | 来源:发表于2022-07-08 00:12 被阅读0次

    本篇分享在ggplot的散点聚类图中,为每个类群添加标签Label的方法,方法通过kmeans方法计算每个簇的中心,给每个簇的中心点添加Class_label实现每个簇的标签标记。

    点图绘图数据

    > data.plot
             tissue   x   y  imagerow imagecol Class
    BIN_001       1   12 22        1      001 class_A
    BIN_002       1   22 21        1      002 class_A
    BIN_003       1   11 32        1      003 class_B
    BIN_004       1   30 14        1      004 class_C
    BIN_005       1   32 45        1      005 class_A
    ...
    

    1、kmeans计算每个簇的中心点坐标

    计算一个簇的中心,首先根据簇类别对数据集分组,然后用kmeans计算每个簇的一个中心坐标。

    library(dplyr);library(purrr);library(ggplot2)
    data.plot %>% 
        group_by(Class) %>% 
        do(model = kmeans(.[c('x', 'y')], 1)) %>% ### kmeans 计算一个中心点
        ungroup() %>% group_by(Class) %>% 
        do(map_df(.$model, broom::tidy)) %>% ### 整理模型数据
        ungroup() %>% select(Class,x,y ) %>% data.frame() %>% 
        dplyr::rename(x.center=x,y.center=y,Class=Class) ->label.data
    
    > label.data
         Class  x.center  y.center
    1   class_A 13.67994  21.90958
    2   class_B 28.67363  38.40217
    3   class_C 16.99799  13.78242
    

    2、画散点图,通过geom_label显示标签信息

    data.plot %>% ggplot(aes(x ,y)) + 
        geom_point(aes(colour = Class),size = 0.5) + 
        scale_colour_brewer(palette = "Dark2") +
        theme_bw() +
        ggtitle("Class.cluster.plot") + theme(plot.title = element_text(face = 2,size = 50,hjust = 0.5)) + 
        geom_label(data = label.data, aes(label = Class,x = x.center,y = y.center))
    

    相关文章

      网友评论

          本文标题:ggplot-geom_point 聚类散点图添加簇标签

          本文链接:https://www.haomeiwen.com/subject/ecepbrtx.html