Dendrogram

Cutoff Line Clusters Dark

Dendrogram with horizontal cutoff line and shaded clusters

Output
Cutoff Line 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 Polygon

np.random.seed(321)

labels = ['P' + str(i) for i in range(1, 15)]
data = np.random.rand(len(labels), 6) * 70
Z = linkage(data, method='ward')

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

cutoff = 0.6 * max(Z[:,2])

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

dn = dendrogram(Z, labels=labels, leaf_rotation=45, leaf_font_size=10,
                color_threshold=cutoff, above_threshold_color='#555555', ax=ax)

# Add cutoff line with glow
for lw, alpha in [(8, 0.1), (4, 0.3), (2, 0.8)]:
    ax.axhline(y=cutoff, color='#F5276C', linewidth=lw, alpha=alpha, linestyle='--' if lw == 2 else '-')

# Shade area below cutoff
ax.fill_between([ax.get_xlim()[0], ax.get_xlim()[1]], 0, cutoff, 
                color='#27D3F5', alpha=0.08, zorder=0)

ax.annotate('Cluster Cutoff', xy=(ax.get_xlim()[1]-10, cutoff), 
            color='#F5276C', fontsize=10, va='bottom')

ax.set_title('Dendrogram with Cluster Cutoff Threshold', fontsize=15, 
             color='white', fontweight='bold', pad=20)
ax.set_xlabel('Points', fontsize=11, color='#888888')
ax.set_ylabel('Ward 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