Dendrogram

Cluster Highlight Dendrogram Dark

Dendrogram with colored rectangular cluster highlights

Output
Cluster Highlight Dendrogram 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(42)

labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
data = np.random.rand(len(labels), 5) * 100
Z = linkage(data, method='ward')

fig, ax = plt.subplots(figsize=(14, 8), facecolor='#0a0a0f')
ax.set_facecolor('#0a0a0f')

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

dn = dendrogram(Z, labels=labels, leaf_rotation=0, leaf_font_size=11,
                color_threshold=0.5*max(Z[:,2]), above_threshold_color='#444444', ax=ax)

# Add colored rectangles for clusters
clusters = fcluster(Z, t=3, criterion='maxclust')
colors = ['#F5276C33', '#27D3F533', '#6CF52733']
ivl = dn['ivl']
leaves = dn['leaves']

cluster_ranges = {}
for i, (leaf, label) in enumerate(zip(leaves, ivl)):
    c = clusters[leaf]
    if c not in cluster_ranges:
        cluster_ranges[c] = [i, i]
    else:
        cluster_ranges[c][1] = i

for c, (start, end) in cluster_ranges.items():
    rect = Rectangle((start*10 - 5, 0), (end - start + 1)*10, max(Z[:,2])*0.95,
                     facecolor=colors[(c-1) % len(colors)], edgecolor='none', zorder=0)
    ax.add_patch(rect)

ax.set_title('Hierarchical Clustering with Cluster Highlights', fontsize=15, 
             color='white', fontweight='bold', pad=20)
ax.set_xlabel('Samples', fontsize=11, color='#888888')
ax.set_ylabel('Distance', 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