如何从 MATLAB 中的树状图中获取颜色?
Posted
技术标签:
【中文标题】如何从 MATLAB 中的树状图中获取颜色?【英文标题】:How to get colors from dendrogram in MATLAB? 【发布时间】:2021-07-09 14:28:21 【问题描述】:我已经生成了一些示例数据的树状图,我想为我的观察结果分配颜色。
下面是如何将颜色从树状图匹配到观察结果的示例。
clear; close all; clc;
%% Generate example data
rng('default') % For reproducibility
N = 10; % number of observations
X = rand(N,3);
%% Get linkage
tree = linkage(X, 'average');
%% Get desired number of clusters
nClusters = 2;
cutoff = median([tree(end-nClusters+1,3) tree(end-nClusters+2, 3)]);
%% plot tree
figure
h = dendrogram(tree, 'ColorThreshold', cutoff); % h contains Line objects with the 'Color' property
【问题讨论】:
【参考方案1】:您需要在代码中添加以下内容:
%% get colors
linesColor = cell2mat(get(h,'Color')); % get lines color;
colorList = unique(linesColor, 'rows');
% NOTE that each row is single line corresponding to the same row in tree
% variable. I use that property below.
X_color = zeros(N,3);
X_cluster = zeros(N,1);
for iLeaf = 1:N
[iRow, ~] = find(tree==iLeaf);
color = linesColor(iRow,:); % !
% assign color to each observation
X_color(iLeaf,:) = color;
% assign cluster number to each observation
X_cluster(iLeaf,:) = find(ismember(colorList, color, 'rows'));
end
【讨论】:
以上是关于如何从 MATLAB 中的树状图中获取颜色?的主要内容,如果未能解决你的问题,请参考以下文章
从 R 中的切割树状图中提取标签成员资格/分类(即:树状图的 cutree 函数)