Dendrogram

Horizontal Banded Clusters Dark

Horizontal dendrogram with colored cluster bands

Output
Horizontal Banded Clusters Dark
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='#0a0a0f')
ax.set_facecolor('#0a0a0f')

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='#555555', ax=ax)

# Add colored bands for clusters
clusters = fcluster(Z, t=3, criterion='maxclust')
band_colors = ['#F5276C20', '#27D3F520', '#6CF52720']

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 with Bands', fontsize=15, 
             color='white', fontweight='bold', pad=15)
ax.set_xlabel('Distance', fontsize=11, color='#888888')
ax.set_ylabel('Items', fontsize=11, color='#888888')
ax.tick_params(axis='both', colors='#888888', labelsize=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#333333')
ax.spines['bottom'].set_color('#333333')

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Statistical

Did this help you?

Support PyLucid to keep it free & growing

Support