わかりました、これは非常にハックな解決策です。もっと良いものがあると確信していますが、これは最初の刺し傷なので、我慢してください。
アイデアは、dend
オブジェクト (内部的にはリスト) でそれぞれの要素名 (この場合は数字のみ) を検索し、対応する色を抽出してデータ フレームに保存し、これを凡例に使用することです。
# First we'll extract the elements and corresponding categories...
categories <- cutree(dend, k = 5)
# ... and save them in a data frame
categories_df <- data.frame(elements = as.numeric(names(categories)),
categories = categories,
color = NA)
# now here's a little function that extracts the color for each element
# from the 'dend' object. It uses the list.search() function from the
# 'rlist' package
library(rlist)
extract_color <- function(element_no, dend_obj) {
dend.search <- list.search(dend_obj, all(. == element_no))
color <- attr(dend.search[[1]], "edgePar")$col
return(color)
}
# I use 'dplyr' to manipulate the data
library(dplyr)
categories_df <- categories_df %>%
group_by(elements) %>%
mutate(color = extract_color(elements, dend))
これにより、次のデータフレームが得られます。
> categories_df
Source: local data frame [40 x 3]
Groups: elements [40]
elements categories color
(dbl) (int) (chr)
1 1 1 #CB410B
2 2 1 #CB410B
3 3 1 #CB410B
4 4 1 #CB410B
5 5 1 #CB410B
6 6 2 #009000
7 7 1 #CB410B
8 8 1 #CB410B
9 9 3 #007FFF
10 10 1 #CB410B
.. ... ... ...
これを、カテゴリの色のみを含むデータ フレームにまとめることができます。
legend_data <- categories_df %>%
group_by(categories) %>%
summarise(color = unique(color))
> legend_data
Source: local data frame [5 x 2]
categories color
(int) (chr)
1 1 #CB410B
2 2 #009000
3 3 #007FFF
4 4 #FF033E
5 5 #3B444B
凡例を簡単に生成できるようになりました。
circlize_dendrogram(dend)
legend(-1.05, 1.05, legend = legend_data$categories, fill = legend_data$color, cex = 0.7)
これにより、次のことが得られます。

cutree(dend, k = 5)
カテゴリの色の数字が各要素のカテゴリに対応していることを確認するために使用できます。