Dendrogram with custom colouring
Mostra commenti meno recenti
Hi, I am preparing dendrograms in MATLAB. I can set the colour threshold as follows:
>> figure()
H = dendrogram(tree,0,'ColorThreshold',1);
set(H,'LineWidth',1.5)
this gives the following output:

I have two questions regarding the above:
1) How can I have MATLAB only colour the largest cluster below my threshold (this would be the one in red)
2) How can I specify the colour
Thanks in advance.
Risposta accettata
Più risposte (1)
micholeodon
il 14 Apr 2021
Modificato: micholeodon
il 14 Apr 2021
Here is how you get colors from your dendrogram and link it with the observations.
By changing 'Color' property in lines stored in h variable below you can change colors in your dendrogram.
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
%% 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
%% changing lines color
h(5).Color = [0 1 0]
2 Commenti
Niraj Desai
il 2 Mar 2023
Thank you! I've been going in circles all afternoon trying to figure this out. Much obliged.
I don't think this works if you have more than 30 data points, since then you have more data points than leaves, and your code errors during the for loop.
For your code to work, you need to provide N as an additional input to dendrogram() to define the Maximum number of leaf nodes.
Categorie
Scopri di più su Surface and Mesh Plots in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!