gpt4 book ai didi

r - 在 r 中为带有彩色叶子的树状图创建图例

转载 作者:行者123 更新时间:2023-12-04 17:24:34 24 4
gpt4 key购买 nike

我在树状图中给叶子上色如下

require(graphics)

dm <- hclust(dist(USArrests[1:5,]), "ave")

df<-data.frame("State"=c("Alabama","Alaska","Arizona","Arkansas","California"), "Location"=c("South","North","West","South","West"))


color.sites<-function(dm){
dend<-as.dendrogram(dm)
plot(dend)

cols <- attributes(dend)
df$ColorGroups <- factor(df$Location)

#Set colour pallette
Location.Pal <- rainbow(nlevels(df$ColorGroups), s=0.9,v=0.9,start=0.1,end=0.9,alpha=1)

colorleaves <- function (n) {
# only apply to "leaves" in other words the labels
if(is.leaf(n)) {
i <- which(df$State == attr(n,"label"))
col.lab <- Location.Pal[[unclass(df$ColorGroups[[i]])]]
a <- attributes(n)
attr(n, "nodePar") <- c(a$nodePar, list(lab.col = col.lab))
}
n
}

xx <- dendrapply(dend, colorleaves)

plot(xx, cex=3, cex.main=2, cex.lab=5, cex.axis=1, mar=c(3,3,3,3), main="Title")
}

color.sites(dm)

enter image description here

我想要:
1)添加解释颜色的图例(即橙色=北)
2) 使叶子标签更大更粗(cex.lab 似乎没有做这项工作)
3) 创建一个具有鲜明对比颜色的调色板(彩虹、热.颜色等,当树状图中有许多叶子和颜色时,它们似乎都混合在一起。

任何意见是极大的赞赏 !

最佳答案

如果您已经知道如何使用和调整 ggplot2 图形,另一种解决方案是使用 @Andrie ggdendro package

library(ggplot2)
library(ggdendro)

dm <- hclust(dist(USArrests[1:5,]), "ave")

df <- data.frame(State = c("Alabama","Alaska","Arizona","Arkansas","California"),
Location = c("South","North","West","South","West"))


hcdata<- dendro_data(dm, type="rectangle")

hcdata$labels <- merge(x = hcdata$labels, y = df, by.x = "label", by.y = "State")


ggplot() +
geom_segment(data=segment(hcdata), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data = label(hcdata), aes(x=x, y=y, label=label, colour = Location, hjust=0), size=3) +
geom_point(data = label(hcdata), aes(x=x, y=y), size=3, shape = 21) +
coord_flip() +
scale_y_reverse(expand=c(0.2, 0)) +
scale_colour_brewer(palette = "Dark2") +
theme_dendro()

enter image description here

关于r - 在 r 中为带有彩色叶子的树状图创建图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11967880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com