Dendrogram

Bottom Fill Areas Light

Light dendrogram with filled areas from bottom to cutoff

Output
Bottom Fill Areas 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(258)

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

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

cutoff = 0.45 * 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='#9ca3af', ax=ax)

# Fill from bottom
clusters = fcluster(Z, t=cutoff, criterion='distance')
fill_colors = ['#F5276C20', '#27D3F520', '#6CF52720', '#F5B02720', '#5314E620']
leaves = dn['leaves']

cluster_ranges = {}
for i, leaf in enumerate(leaves):
    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():
    color = fill_colors[(c-1) % len(fill_colors)]
    edge = color.replace('20', '')
    rect = Rectangle((start*10 - 5, 0), (end - start + 1)*10, cutoff,
                     facecolor=color, edgecolor=edge, linewidth=1, zorder=0)
    ax.add_patch(rect)

ax.axhline(y=cutoff, color='#9ca3af', linewidth=1, linestyle=':', alpha=0.5)

ax.set_title('Cluster Membership with Bottom Fill', fontsize=15, 
             color='#1f2937', fontweight='bold', pad=20)
ax.set_xlabel('Variables', fontsize=11, color='#374151')
ax.set_ylabel('Distance', 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