Dan
Dan

Reputation: 45751

How to change the cluster colours in a dendrogram

How can I change the colours assigned to each cluster in a MATLAB dendrogram to match my own custom colour scheme? Extensive googling has not yielded a solution.

Upvotes: 0

Views: 1557

Answers (1)

Dan
Dan

Reputation: 45751

%%// Hierarchical clustering
T = linkage(data,'average','spearman');
D = pdist(data, 'spearman');
leafOrder = optimalleaforder(T, D);
th = 0.726;
H = dendrogram(T, 0,'ReOrder', leafOrder, 'Orientation', 'left', 'ColorThreshold', th);
h = gca;
set(h, 'YTickLabel', labels(leafOrder));

%// Changing the colours
lineColours = cell2mat(get(H,'Color'));
colourList = unique(lineColours, 'rows');

myColours = [230,186,0;
             127,127,127;
             10,35,140;
             176,0,0;
             158,182,72;
             79,129,189;
             209,99,9;
             4,122,146]/255;

%// Replace each colour (colour by colour). Start from 2 because the first colour are the "unclustered" black lines             
for colour = 2:size(colourList,1)
    %// Find which lines match this colour
    idx = ismember(lineColours, colourList(colour,:), 'rows');
    %// Replace the colour for those lines
    lineColours(idx, :) = repmat(myColours(colour-1,:),sum(idx),1);
end
%// Apply the new colours to the chart's line objects (line by line)
for line = 1:size(H,1)
    set(H(line), 'Color', lineColours(line,:));
end

Upvotes: 1

Related Questions