如何在MATLAB中从树状图中获取颜色



我已经生成了一些示例数据的树状图,我想为我的观察结果分配颜色。

下面是关于如何将树状图中的颜色与观测值相匹配的示例。

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

以下是您需要添加到代码中的内容:

%% 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

相关内容

  • 没有找到相关文章

最新更新