我try 使用iris个数据集显示截止高度对聚类数的影响,并使用rect.dendrogram可视化得到的聚类数.

if (!require("dendextend")) {install.packages("dendextend")} else {library("dendextend")}

data("iris", package = "datasets")

Data <- list()

Data$Lab <- as.character(iris[,5])
Data$dat <- prcomp(iris[,-5])$x[,1:2]

Data$dist <- dist(Data$dat, method = "euclidean")
Data$hist <- hclust(Data$dist, method = "complete")

# plot dendrogram

hcd <- as.dendrogram(Data$hist)

cluster.height <- 6

par(pty = "m",
    mar = c(1,2,1.5,1),
    mgp = c(1,0,0),
    tck = 0.01,
    cex.axis = 0.75,
    font.main = 1)
plot(sort(hcd), 
     ylab = "Height",
     leaflab = "none")
rect.dendrogram(sort(hcd),
                h = cluster.height,
                border = "black",
                xpd = NA,
                lower_rect = -0.1,
                upper_rect = 0)
abline(h = cluster.height,
       lty = 3)
dev.off()

使用高度值时,会出现两个矩形.

dendrogram_1

该函数搜索由中断创建的簇. 问题是,是否有办法只获得较大的矩形? 有没有我忽略的参数/选项,或者是rect.dendrogram函数中的错误?

推荐答案

在我看来确实像是某种错误,至少该函数似乎只适用于"hclust"个对象,而不适用于"dendrogram"个对象.您可以使用该函数的相关部分.

> rect_dnd <- \(tree, which, h, ybadj=0, ytadj=0, ...) {
+   cl <- cutree(tree, h=h)
+   clt <- table(cl)[unique(cl[tree$order])]
+   m <- c(0, cumsum(clt))
+   k <- min(which(rev(tree$height) < h))
+   rect(xleft=m[which] + 0.66,
+        ybottom=mean(rev(tree$height)[(k - 1):k]) + ytadj,
+        xright=m[which + 1] + 0.33,
+        ytop=par()$usr[3] + ybadj, ...)
+ }
> 
> cluster.height <- 6
> 
> par(pty="m", mar=c(1, 2, 1.5, 1), mgp=c(1, 0, 0), tck=0.01, cex.axis=0.75, 
+     font.main=1)
> plot(hcd, ylab="Height", leaflab="none")
> rect_dnd(Data$hist, which=1, h=cluster.height, ytadj=-.1, border='red')
> abline(h=cluster.height, lty=3)

enter image description here


Data:

> Data <- list(Lab=as.character(iris[, 5]), dat=prcomp(iris[, -5])$x[, 1:2])
> Data$dist <- dist(Data$dat, method="euclidean")
> Data$hist <- hclust(Data$dist, method="complete")
> hcd <- as.dendrogram(Data$hist)

R相关问答推荐

在边界外添加注释或标题

检测(并替换)字符串中的数学符号

使用tidyverse / Mutate的存款账户余额

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

selectInput不返回ALL,并将因子转换为shiny 的数字

将嵌套列表子集化为嵌套列表

计算具有奇数日期的运行金额

在ggplot中为不同几何体使用不同的 colored颜色 比例

计算满足R中条件的连续列

在GG图中绘制射线的自动程序

更改STAT_VALLES/STAT_PEAKS中的箭头线宽/大小

如何根据R中其他变量的类别汇总值?

我如何go 掉盒子图底部的数字?

如何计算增加10米(0.01公里)的行?

Geom_arcbar()中出错:找不到函数";geom_arcbar";

将列的值乘以在不同数据集中找到的值

构建一个6/49彩票模拟系统

如何在GALT包的函数&geom_x样条线中调整线宽

如何在刻面和翻转堆叠条形图中对齐geom_text()

具有由向量定义的可变步长的序列