用多种颜色标记 ggdendro 叶子

发布于 2024-12-14 08:18:48 字数 110 浏览 4 评论 0原文

我遇到一种情况,我正在绘制带有类标签的数据点的树状图。 我希望看到凝聚聚类将具有相同标签的那些聚集在一起。对标签进行颜色编码可以轻松阅读此类树状图。有没有办法用 R 中的 ggdendro 来实现这一点?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2024-12-21 08:18:49

这篇文章窃取大部分设置...

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))

...并添加分组因素...

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

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

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

<图片src="https://i.sstatic.net/4lF7S.png" alt="在此处输入图像描述">

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

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"))

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

... 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))

enter image description here

(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"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文