我已经建立了一个树状图,并使用dendextend包的set("by_labels_branches_col")函数根据其“纯度”(是否仅包括因子变量中具有特定值的对象)对其分支进行着色。现在,我想将这个树状图转换为ggplot2对象,以便进一步定制。我已经能够使用函数as.ggdend (也来自dendextend包)做到这一点。以下是我遇到的两个问题,我需要一些帮助:
1-使用as.ggdend后,生成的对象将“丢失”指示树状图高度的垂直轴...如何才能在不丢失轴的情况下进行此变换?
2.-我还尝试通过使用dendextend包的colored_bars函数添加一个彩色条形图来丰富我的树状图。但是,我不知道如何保存生成的对象以将其转换为ggplot对象。
在这里,我提供了一个使用mtcar数据集的代码示例
df=mtcars
ds=dist(df, "euclidean")
hc<-hclust(ds,method= "average")
de=as.dendrogram(hc)
library(dendextend)
code=rownames(df[df$cyl==4,])#factor for coloring
de2<-de%>%set("by_labels_branches_col", value = c(code))%>% set("labels", "")%>%as.dendrogram(de)#coloring branches
#to add the colored bar
colores<-c("red","black", "blue") [as.factor(df$cyl)]
plot(de2)
colored_bars(colors=colores,dend=de2, y_shift=-2, rowLabels="" )
#transform to ggplot
de3=as.ggdend(de2)提前感谢您的任何可能的答复
发布于 2021-05-06 17:14:43
最后,我找到了第一个问题的解决方案)。它远不是优雅的,也许还有更好的方法来做到这一点。然而,我把它贴在这里,以防有人发现它有用。
该解决方案跳过了as.ggdend的使用,直接使用ggplot+theme来确保显示树状图轴。由于这会自动加宽所有绘图线,因此在步骤2/3中会更正线的大小。
step1=ggplot(de2)+
theme(axis.line.y = element_line(color="black"),
axis.text.y = element_text(color="black"),
axis.ticks.y = element_line(color="black"))+
scale_y_continuous(expand = expansion(add = c(0,0)))
step2=ggplot_build(step1)
step2$data[[1]]$size=0.3
step3= ggplot_gtable(step2)
step4=ggplotify::as.ggplot(step3)https://stackoverflow.com/questions/67216498
复制相似问题