Custom cluster colors of SciPy dendrogram in Python (link_color_func?)

后端 未结 3 1290
感情败类
感情败类 2020-12-28 08:42

I want to color my clusters with a color map that I made in the form of a dictionary (i.e. {leaf: color}).

I\'ve tried following https://joernhees.de/

3条回答
  •  無奈伤痛
    2020-12-28 09:06

    I found a hackish solution, and does require to use the color threshold (but I need to use it in order to obtain the same original coloring, otherwise the colors are not the same as presented in the OP), but could lead you to a solution. However, you may not have enough information to know how to set the color palette order.

    # Init
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns; sns.set()
    
    # Load data
    from sklearn.datasets import load_diabetes
    
    # Clustering
    from scipy.cluster.hierarchy import dendrogram, fcluster, leaves_list, set_link_color_palette
    from scipy.spatial import distance
    from fastcluster import linkage # You can use SciPy one too
    
    %matplotlib inline
    # Dataset
    A_data = load_diabetes().data
    DF_diabetes = pd.DataFrame(A_data, columns = ["attr_%d" % j for j in range(A_data.shape[1])])
    
    # Absolute value of correlation matrix, then subtract from 1 for disimilarity
    DF_dism = 1 - np.abs(DF_diabetes.corr())
    
    # Compute average linkage
    A_dist = distance.squareform(DF_dism.as_matrix())
    Z = linkage(A_dist,method="average")
    
    # Color mapping dict not relevant in this case
    # Dendrogram
    # To get this dendrogram coloring below  `color_threshold=0.7`
    #Change the color palette, I did not include the grey, which is used above the threshold
    set_link_color_palette(["#B061FF", "#61ffff"])
    D = dendrogram(Z=Z, labels=DF_dism.index, color_threshold=.7, leaf_font_size=12, leaf_rotation=45, 
                   above_threshold_color="grey")
    

    The result:

提交回复
热议问题