标记ggdendro叶子多种颜色 [英] Labelling ggdendro leaves in multiple colors

查看:570
本文介绍了标记ggdendro叶子多种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况,我在绘制一个树状图与数据点与类标签。
我希望看到聚集聚类将那些具有相同标签的聚类组合在一起。对标签进行颜色编码使得易于读取这样的树形图。有没有办法,我们可以实现这与ggdendro在R?

I have a situation in which i am plotting a dendrogram with data points that come with class labels. I wish to see that agglomerative clustering groups those with the same label together. Color coding the labels makes it easy to read such a dendrogram. Is there a way we can achieve this with ggdendro in R ?

推荐答案


Stealing most of the setup from this post ...

library(ggplot2)
library(ggdendro)
data(mtcars)
x <- as.matrix(scale(mtcars))
dd.row <- as.dendrogram(hclust(dist(t(x))))
ddata_x <- dendro_data(dd.row)

p2 <- ggplot(segment(ddata_x)) +
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend))

...并添加分组因子...

... and adding a grouping factor ...

labs <- label(ddata_x)
labs$group <- c(rep("Clust1", 5), rep("Clust2", 2), rep("Clust3", 4))
labs
#     x y text  group
# 1   1 0 carb Clust1
# 2   2 0   wt Clust1
# 3   3 0   hp Clust1
# 4   4 0  cyl Clust1
# 5   5 0 disp Clust1
# 6   6 0 qsec Clust2
# 7   7 0   vs Clust2
# 8   8 0  mpg Clust3
# 9   9 0 drat Clust3
# 10 10 0   am Clust3
# 11 11 0 gear Clust3

...您可以使用 aes color =)参数 geom_text()为您的标签着色:

... you can use the aes(colour=) argument to geom_text() to color your labels:

p2 + geom_text(data=label(ddata_x),
               aes(label=label, x=x, y=0, colour=labs$group))

(如果您想提供自己的颜色,可以使用 scale_colour_manual()这个:

(If you want to supply your own colors, you can use scale_colour_manual(), doing something like this:

p2 + geom_text(data=label(ddata_x),
               aes(label=label, x=x, y=0, colour=labs$group)) +
     scale_colour_manual(values=c("blue", "orange", "darkgreen"))

这篇关于标记ggdendro叶子多种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆