1

最初,我尝试使用来自dendextend 的colored_bars 将水平颜色侧栏添加到树状图(而不是整个热图)。

下面的代码(感谢您的帮助,Tal!)运行良好。剩下的唯一问题是如何控制栏与叶子标签的距离和栏的宽度?

这是一个例子,数据和代码
数据(4个变量,5个案例)

df <- read.table(header=T, text="group class v1 v2 
1          A         1          3.98         23.2  
2          A         2          5.37         18.5  
3          C         1          4.73         22.1  
4          B         1          4.17         22.3  
5          C         2          4.47         22.4  
") 

car_type <- factor(df[,c(1)]) # groups codes (A,B,C)  
cols_4 <- heat.colors(3)  
col_car_type <- cols_4[car_type] 
matrix<-data.matrix(df[,c(3,4)])
rnames<-df[,2]
row.names(matrix)<-rnames
matrix<-data.matrix(df[,c(3,4)])
row.names(matrix)<-rnames
dend<-hclust(dist(matrix))
labels_colors(dend) <- col_car_type[order.dendrogram(dend)]  # Error in order.dendrogram(dend) : 'order.dendrogram' requires a dendrogram
# But I dont think the line above is doing anything so it can be removed...
plot(dend)  
colored_bars(col_car_type, dend)
4

1 回答 1

3

使用dendextend可以做到这一点。

首先安装最新的 dendextend 版本,您可以使用:

install.packages(dendextend)

这是使用 mtcars 的示例:

## mtcars example

# Create the dend:
dend <- as.dendrogram(hclust(dist(mtcars)))

# Create a vector giving a color for each car to which company it belongs to
car_type <- rep("Other", length(rownames(mtcars)))
is_x <- grepl("Merc", rownames(mtcars))
car_type[is_x] <- "Mercedes"
is_x <- grepl("Mazda", rownames(mtcars))
car_type[is_x] <- "Mazda"
is_x <- grepl("Toyota", rownames(mtcars))
car_type[is_x] <- "Toyota"
car_type <- factor(car_type)
n_car_types <- length(unique(car_type))
cols_4 <- colorspace::rainbow_hcl(n_car_types, c = 70, l  = 50)
col_car_type <- cols_4[car_type]

# extra: showing the various clusters cuts 
k234 <- cutree(dend, k = 2:4)

# color labels by car company:
labels_colors(dend) <- col_car_type[order.dendrogram(dend)]
# color branches based on cutting the tree into 4 clusters:
dend <- color_branches(dend, k = 4)

### plots
par(mar = c(12,4,1,1))
plot(dend)
colored_bars(cbind(k234[,3:1], col_car_type), dend, rowLabels = c(paste0("k = ", 4:2), "Car Type"))

# horiz version:
par(mar = c(4,1,1,12))
plot(dend, horiz = TRUE)
colored_bars(cbind(k234[,3:1], col_car_type), dend, rowLabels = c(paste0("k = ", 4:2), "Car Type"), horiz = TRUE)
legend("topleft", legend = levels(car_type), fill = cols_4)

在此处输入图像描述

于 2016-01-01T16:32:42.653 回答