在r中创建带彩色叶子的树状图图例
我已经在树状图中给叶子着色,如下所示在r中创建带彩色叶子的树状图图例,r,plot,legend,hclust,R,Plot,Legend,Hclust,我已经在树状图中给叶子着色,如下所示 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(
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)
require(图形)
dm
使用legend()
将整个函数源复制到编辑器中并进行编辑以执行所需操作,然后将其分配给您自己的函数对象并使用它。如果由于找不到函数(它们可能未从名称空间中导出)而失败,请使用ns::
找出它是哪个名称空间的前缀,其中ns
是相关的名称空间
尝试使用包中的一个选项来选择分类调色板
如果您已经知道如何使用和调整ggplot2图形,另一个解决方案是使用@Andrie
库(ggplot2)
图书馆(GGO)
dm请尝试将自己限制在每篇文章1个问题。多个问题都可以,只要将它们链接在一起以显示它们是相关的。在以后的文章中,请记住这一点。+1这可能是第一次,以便有人(我以外的人)使用ggdendro
@Andrie发布解决方案:再次感谢ggdendro
!!这是一个很好的包,可以管理树状结构,并使用流行的ggplot2
@Dickoa绘制它们。感谢您让我了解ggdendro包。我需要像示例中一样显示高度,还需要树状图保持不变。排除coord_flip()会导致树状图倒置。如何使用ggdendro,但方向与示例中相同,并且y轴上显示高度?再次感谢。
cols <- c("orange","forestgreen")
legend("topright", legend = c("North","South"),
fill = cols, border = cols, bty = "n")
if (!is.null(et <- attr(x, "edgetext"))) {
my <- mean(hgt, yTop)
if (horiz)
text(my, x0, et)
else text(x0, my, et)
}
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()