Dendrogram with custom colouring
조회 수: 28 (최근 30일)
이전 댓글 표시
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/160694/image.jpeg)
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.
댓글 수: 0
채택된 답변
Adam
2017년 2월 14일
If you use the
hLines = dendrogram(...)
syntax you will get an array of handles as output. These will be handles to the lines created. These can be coloured individually and with any colour you want. I assume the lines are ordered as specified by the leafOrder although I haven't checked.
X = rand(10,3);
tree = linkage(X,'average');
D = pdist(X);
leafOrder = optimalleaforder(tree,D);
figure()
h = dendrogram(tree,'Reorder',leafOrder);
h(1).Color = 'r';
h(8).Color = [0 0.5 0];
추가 답변 (1개)
micholeodon
2021년 4월 14일
편집: micholeodon
2021년 4월 14일
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
Niraj Desai
2023년 3월 2일
Thank you! I've been going in circles all afternoon trying to figure this out. Much obliged.
T0m07
2023년 5월 22일
편집: T0m07
2023년 5월 22일
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.
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!