How to get colors from dendrogram in MATLAB?

Viewed 58

I have generated the dendrogram of some examplary data and I want to get colors assigned to my observations.

Here below is the example on how to match colors from dendrogram to observations.

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 Answers

Here what you need to add to your code:

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