ggplot 的聚类树状图中未显示 X 轴标签

X axis label is not showing in clustering dendrogram in ggplot

我按照之前在网上找到的代码做了聚类树状图,但是图中没有显示 x 轴。我想在 x 轴上显示差异值,但我没有成功。

females<-cervidae[cervidae$Sex=="female",]
dstf   <- daisy(females[,9:14], metric = "euclidean", stand = FALSE)
hcaf   <- hclust(dstf, method = "ave")
k     <- 3
clustf <- cutree(hcaf,k=k)  # k clusters


dendrf    <- dendro_data(hcaf, type="rectangle") # convert for ggplot
clust.dff <- data.frame(label=rownames(females), cluster=factor(clustf), 
females$Genus, females$Species) 
dendrf[["labels"]]   <- merge(dendrf[["labels"]],clust.dff, by="label")
rectf <- aggregate(x~cluster,label(dendrf),range)
rectf <- data.frame(rectf$cluster,rectf$x)
ymax <- mean(hcaf$height[length(hcaf$height)-((k-2):(k-1))])


fem=ggplot() + 
   geom_segment(data=segment(dendrf), aes(x=x, y=y, xend=xend, yend=yend)) + 
   geom_text(data=label(dendrf), aes(x, y, label= females.Genus, hjust=0, 
   color=females.Genus),
        size=3) +
   geom_rect(data=rectf, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax), 
        color="red", fill=NA)+
   coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
   theme_dendro() + scale_color_discrete(name="Genus") + 
   theme(legend.position="none")

这是我的树状图的样子:

您的代码包含 theme_dendro(),其帮助文件中将其描述为:

Sets most of the ggplot options to blank, by returning blank theme elements for the panel grid, panel background, axis title, axis text, axis line and axis ticks.

您强制 x 轴线/文本/刻度在 theme() 中可见:

ggplot() + 
  geom_segment(data=segment(dendrf), aes(x=x, y=y, xend=xend, yend=yend)) +
  geom_text(data=label(dendrf), aes(x, y, label= label, hjust=0,
                                    color=cluster),
            size=3) +
  geom_rect(data=rectf, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax),
            color="red", fill=NA)+
  coord_flip() +
  scale_y_reverse(expand=c(0.2, 0)) + 
  theme_dendro() +
  scale_color_discrete(name="Cluster") +
  theme(legend.position="none",
        axis.text.x = element_text(),  # show x-axis labels
        axis.ticks.x = element_line(), # show x-axis tick marks
        axis.line.x = element_line())  # show x-axis lines

(此演示使用内置数据集,因为我不确定什么是鹿科动物。用于创建它的代码转载如下:)

library(cluster); library(ggdendro); library(ggplot2)

hcaf   <- hclust(dist(USArrests), "ave")
k     <- 3
clustf <- cutree(hcaf,k=k)  # k clusters

dendrf    <- dendro_data(hcaf, type="rectangle") # convert for ggplot
clust.dff <- data.frame(label=rownames(USArrests), 
                        cluster=factor(clustf)) 
dendrf[["labels"]]   <- merge(dendrf[["labels"]],clust.dff, by="label")
rectf <- aggregate(x~cluster,label(dendrf),range)
rectf <- data.frame(rectf$cluster,rectf$x)
ymax <- mean(hcaf$height[length(hcaf$height)-((k-2):(k-1))])