Heatmap

Customer Segment Clustermap

Hierarchical clustering of customer behavior metrics

Output
Customer Segment Clustermap
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, leaves_list
from scipy.spatial.distance import pdist
from matplotlib.colors import LinearSegmentedColormap

np.random.seed(456)
data = np.random.randn(10, 8)
data[0:2, :4] += 2.5
data[4:7, :] -= 1.8
data[8, :] += 1.5

colors = ['#7c3aed', '#a78bfa', '#ede9fe', '#ffffff', '#d1fae5', '#34d399', '#059669']
cmap = LinearSegmentedColormap.from_list('VioletEmerald', colors, N=256)

row_linkage = linkage(pdist(data), method='ward')
col_linkage = linkage(pdist(data.T), method='ward')
row_order = leaves_list(row_linkage)
col_order = leaves_list(col_linkage)
data_ordered = data[row_order][:, col_order]

fig = plt.figure(figsize=(9, 9), facecolor='white')

ax_heatmap = fig.add_axes([0.2, 0.1, 0.6, 0.6])
ax_col_dend = fig.add_axes([0.2, 0.71, 0.6, 0.15])
ax_row_dend = fig.add_axes([0.04, 0.1, 0.15, 0.6])
ax_cbar = fig.add_axes([0.83, 0.3, 0.03, 0.2])

im = ax_heatmap.imshow(data_ordered, cmap=cmap, aspect='auto', vmin=-3, vmax=3)
ax_heatmap.set_xticks([])
ax_heatmap.set_yticks([])
for spine in ax_heatmap.spines.values():
    spine.set_linewidth(0.5)
    spine.set_color('#cccccc')

dendrogram(col_linkage, ax=ax_col_dend, color_threshold=0, above_threshold_color='k',
           link_color_func=lambda k: 'k', no_labels=True)
ax_col_dend.axis('off')

dendrogram(row_linkage, ax=ax_row_dend, orientation='left', color_threshold=0,
           above_threshold_color='k', link_color_func=lambda k: 'k', no_labels=True)
ax_row_dend.axis('off')

cbar = plt.colorbar(im, cax=ax_cbar)
cbar.outline.set_linewidth(0.5)
cbar.ax.tick_params(labelsize=9, width=0.5)
cbar.set_label('Z-Score', fontsize=10)

ax_col_dend.set_title('Metrics', fontsize=11, pad=5)
ax_row_dend.set_ylabel('Segments', fontsize=11, labelpad=10)
ax_row_dend.yaxis.set_label_position('left')

plt.show()
Library

Matplotlib

Category

Heatmaps & Density

Did this help you?

Support PyLucid to keep it free & growing

Support