Dendrogram

Multi-threshold Zones Dark

Dendrogram with multiple threshold zones highlighted

Output
Multi-threshold Zones Dark
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, set_link_color_palette

np.random.seed(987)

labels = ['Obs_' + str(i) for i in range(1, 17)]
data = np.random.rand(len(labels), 5) * 100
Z = linkage(data, method='ward')

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

max_d = max(Z[:,2])
thresholds = [0.3*max_d, 0.5*max_d, 0.7*max_d]
zone_colors = ['#6CF52715', '#27D3F515', '#F5B02715', '#F5276C15']

# Fill zones
ax.fill_between([0, 160], 0, thresholds[0], color=zone_colors[0], zorder=0)
ax.fill_between([0, 160], thresholds[0], thresholds[1], color=zone_colors[1], zorder=0)
ax.fill_between([0, 160], thresholds[1], thresholds[2], color=zone_colors[2], zorder=0)
ax.fill_between([0, 160], thresholds[2], max_d*1.05, color=zone_colors[3], zorder=0)

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

dn = dendrogram(Z, labels=labels, leaf_rotation=45, leaf_font_size=9,
                color_threshold=thresholds[1], above_threshold_color='#666666', ax=ax)

# Threshold lines
for t, c in zip(thresholds, ['#6CF527', '#27D3F5', '#F5B027']):
    ax.axhline(y=t, color=c, linewidth=1.5, linestyle='--', alpha=0.7)

ax.set_title('Multi-Level Hierarchical Clustering', fontsize=15, 
             color='white', fontweight='bold', pad=20)
ax.set_xlabel('Observations', fontsize=11, color='#888888')
ax.set_ylabel('Distance', fontsize=11, color='#888888')
ax.tick_params(axis='both', colors='#888888', labelsize=9)
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