Dendrogram

Ellipse Highlight Light

Light theme with elliptical cluster highlights

Output
Ellipse Highlight 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 Ellipse

np.random.seed(147)

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

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

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

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

# Elliptical highlights
clusters = fcluster(Z, t=3, criterion='maxclust')
ellipse_colors = ['#F5276C', '#27D3F5', '#6CF527']
leaves = dn['leaves']

cluster_centers = {}
for i, leaf in enumerate(leaves):
    c = clusters[leaf]
    if c not in cluster_centers:
        cluster_centers[c] = []
    cluster_centers[c].append(i * 10)

for c, positions in cluster_centers.items():
    center_x = np.mean(positions)
    width = (max(positions) - min(positions) + 15)
    color = ellipse_colors[(c-1) % len(ellipse_colors)]
    ellipse = Ellipse((center_x, max(Z[:,2])*0.4), width, max(Z[:,2])*0.7,
                     facecolor=color, edgecolor=color, alpha=0.1, linewidth=2, zorder=0)
    ax.add_patch(ellipse)

ax.set_title('Cluster Analysis with Ellipse Highlights', fontsize=15, 
             color='#1f2937', fontweight='bold', pad=20)
ax.set_xlabel('Clusters', fontsize=11, color='#374151')
ax.set_ylabel('Distance', fontsize=11, color='#374151')
ax.tick_params(axis='both', colors='#374151', labelsize=10)
for spine in ax.spines.values():
    spine.set_visible(False)

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Statistical

Did this help you?

Support PyLucid to keep it free & growing

Support