如何向树状图标签/颜色条添加自定义颜色?

时间:2019-09-13 12:42:20

标签: r plot dendrogram hclust dendextend

我有48个样本用于聚类。这48个样本来自9个组(StudyAccession),每9个组中有2个子组(SampleType)。我希望树状图的叶子标签根据样本所属的子组进行着色。树状图下方添加了一个彩色条,以表示9个组。

为了给标签着色,我使用了以下代码。我在这里添加了for循环,因为我想添加自定义颜色。

#Add colors to label

label_colors_to_use <- as.numeric(factors$SampleType) #Input groups of sample type for label color

label_colors_to_use <- label_colors_to_use[order.dendrogram(dend)] #Order group annotation as per in dendrogram

#Use to add custom label color

for(i in 1:length(label_colors_to_use)){ 

  if(label_colors_to_use[i] == 1){ 

       label_colors_to_use[i] = "blue" 

  }else if(label_colors_to_use[i] == 2){ 

       label_colors_to_use[i] = "red"

  }

 }

现在使用彩色条,我使用了这段代码。在使用功能as.numeric()时,这9个组的编号为1到9,随后根据这些编号获取颜色。

StudyAccession_colors_to_use <- as.numeric(factors$StudyAccession) #Input groups of sample type for label color

StudyAccession_colors_to_use <- StudyAccession_colors_to_use[order.dendrogram(dend)] #Order group annotation as per in dendrogram

colored_bars(colors = StudyAccession_colors_to_use, dend = dend, rowLabels = "Project", sort_by_labels_order = FALSE)

但是,只分配了八种颜色;第九项采用第一种颜色。我可以像之前那样使用for循环更改它,但是会使代码变长。如何缩短代码?

完整代码here可用。

0 个答案:

没有答案