Search code examples
pythonscipyhierarchical-clustering

Simple coloring of Scipy dendrograms


I am trying to create a monochrome (eg., black on white) dendrogram using Scipy. After the Scipy documentation, I have been playing with the set_link_color_pallete function, but kept getting just one of the groups in black, while the remaining of the dendrogram is in blue (see the figure below).

Here is my test code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy

ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
                    400., 754., 564., 138., 219., 869., 669.])
Z = hierarchy.linkage(ytdist, 'single')
hierarchy.set_link_color_palette(['k', 'k', 'k', 'k', 'k'])
dn = hierarchy.dendrogram(Z)
plt.show()

enter image description here

Here is a question that should address this problem, but I could not understand it very clearly.

Any hints or suggestions?


Solution

  • One easy way would be to set a color_threshold at 0 and then set the above_threshold_color to 'k', like this:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.cluster import hierarchy
    
    ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
                        400., 754., 564., 138., 219., 869., 669.])
    Z = hierarchy.linkage(ytdist, 'single')
    dn = hierarchy.dendrogram(Z, color_threshold=0, above_threshold_color='k')
    plt.show()
    

    Monocolor Dendrogram