Dendrogram

Horizontal Colored Bands Light

Light horizontal dendrogram with colored cluster bands

Output
Horizontal Colored Bands Light
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster, set_link_color_palette
from matplotlib.patches import Rectangle

np.random.seed(654)

labels = ['Item_' + str(i) for i in range(1, 13)]
data = np.random.rand(len(labels), 4) * 50
Z = linkage(data, method='average')

fig, ax = plt.subplots(figsize=(12, 9), facecolor='#ffffff')
ax.set_facecolor('#ffffff')

set_link_color_palette(['#27D3F5', '#F5276C', '#6CF527', '#F5B027'])

dn = dendrogram(Z, labels=labels, orientation='right', leaf_font_size=11,
                color_threshold=0.55*max(Z[:,2]), above_threshold_color='#9ca3af', ax=ax)

# Colored bands for clusters
clusters = fcluster(Z, t=3, criterion='maxclust')
band_colors = ['#F5276C15', '#27D3F515', '#6CF52715']

for i, leaf in enumerate(dn['leaves']):
    c = clusters[leaf]
    rect = Rectangle((0, i*10 - 5), max(Z[:,2]), 10,
                     facecolor=band_colors[(c-1) % len(band_colors)], edgecolor='none', zorder=0)
    ax.add_patch(rect)

ax.set_title('Horizontal Cluster Analysis', fontsize=15, 
             color='#1f2937', fontweight='bold', pad=15)
ax.set_xlabel('Distance', fontsize=11, color='#374151')
ax.set_ylabel('Items', fontsize=11, color='#374151')
ax.tick_params(axis='both', colors='#374151', labelsize=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#e5e7eb')
ax.spines['bottom'].set_color('#e5e7eb')

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Statistical

Did this help you?

Support PyLucid to keep it free & growing

Support