Dendrogram
Bottom Fill Clusters Dark
Dendrogram with filled areas from bottom to clusters
Output
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='#0a0a0f')
ax.set_facecolor('#0a0a0f')
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='#555555', ax=ax)
# Fill from bottom to cutoff for each cluster
clusters = fcluster(Z, t=cutoff, criterion='distance')
fill_colors = ['#F5276C25', '#27D3F525', '#6CF52725', '#F5B02725', '#5314E625']
ivl = dn['ivl']
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():
rect = Rectangle((start*10 - 5, 0), (end - start + 1)*10, cutoff,
facecolor=fill_colors[(c-1) % len(fill_colors)],
edgecolor=fill_colors[(c-1) % len(fill_colors)].replace('25', ''),
linewidth=1, zorder=0)
ax.add_patch(rect)
ax.axhline(y=cutoff, color='#888888', linewidth=1, linestyle=':', alpha=0.5)
ax.set_title('Cluster Membership with Bottom Fill', fontsize=15,
color='white', fontweight='bold', pad=20)
ax.set_xlabel('Variables', 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
More Dendrogram examples
☕