0

如何單獨對樹狀圖的標籤着色,以便它們與MATLAB中簇的顏色相匹配?使樹狀圖中的刻度線顏色與簇顏色匹配

下面是一個例子使用的代碼在我的回答下面產生所需的輸出(注意標貼都只是50系統字符系列'A':'r'):

enter image description here

如果有一個更簡單的方法來做到這一點,請發表回答,因爲我無法通過Google搜索找到解決方案。如果沒有,代碼在後面。

回答

0

我找不到一個明確的答案,但我設法從我在網上找到的幾個想法(顯示在評論中)一起把以下內容拼湊起來。希望這對某人有用。

我假設你的數據你聚類是矩陣datalabels存儲在單元陣列稱爲標籤:

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

%First get a list of the colours of each line object 
lineColours = cell2mat(get(H,'Color')); 
colourList = unique(lineColours, 'rows'); 
% For each cluster (i.e. for each unique colour) 
for colour = 1:size(colourList,1) 
    % see http://stackoverflow.com/a/16677119/1011724 for the idea of 
    % copying the axis 
    ax = copyobj(gca, gcf); 
    % see http://undocumentedmatlab.com/blog/customizing-axes-rulers for 
    % more on YRuler. This might not work on older versions of MATLAB. 
    yruler = ax.YRuler; 
    rgb = floor(colourList(colour,:)'*255); 
    % Make all the datalabels of the new axis the current colour. (We will 
    % later make those labels that aren't this colour empty.) 
    yruler.TickLabels.ColorData = uint8([rgb;255]); 
    % Might not be necessary, but stopped me getting errors 
    pause(0.1) 

    % The hard bit is figuring out which line object matches which label 
    % Note that there might be an easier way if you are willing to alter your dendrogram.m file: http://www.mathworks.com/matlabcentral/newsreader/view_thread/134997 
    idx = ismember(lineColours, colourList(colour,:), 'rows'); 
    clusterNodes = [T(idx,1);T(idx,2)]; 
    % Cluster nodes greater than the number of data points are none terminal 
    % nodes and thus not of interest. 
    [~,c]=find(bsxfun(@eq,clusterNodes(clusterNodes < length(labels)+1),leafOrder)) 
    % Convert to a logical index 
    idx = ~ismember(1:(size(lineColours,1)+1), c); 
    n = sum(idx); 
    % Set the labels we don't want to colour (this iteration) to be empty 
    % char arrays. 
    yruler.TickLabels.String(idx) = mat2cell(repmat(char(),n,1),zeros(n,1),0); 
end