Code
| eruptions | waiting | |
|---|---|---|
| 0 | 3.600 | 79 |
| 1 | 1.800 | 54 |
| 2 | 3.333 | 74 |
| 3 | 2.283 | 62 |
| 4 | 4.533 | 85 |
Exploratory Data Analysis & Unsupervised Learning
| eruptions | waiting | |
|---|---|---|
| 0 | 3.600 | 79 |
| 1 | 1.800 | 54 |
| 2 | 3.333 | 74 |
| 3 | 2.283 | 62 |
| 4 | 4.533 | 85 |
Marketing: finding groups of customers with similar behavior given a large database of customer data containing their properties and past buying records.
Biology: classification of plants and animals given their features.
Insurance: identifying groups of motor insurance policy holders with a high average claim cost; identifying frauds, identify potential group of customers, etc.
Bookshops: book ordering (recommendation).
City-planning: identifying groups of houses according to their type, value and geographical location.
Internet: document classification; clustering weblog data to discover groups of similar access patterns; topic modeling…
\[\begin{align*}\color{red}{q}:\mathbb{R}^d&\to\color{blue}{{\cal C}}=\{\color{blue}{c_k}:k=1,...,K\}\\ \text{x}_i&\mapsto \color{red}{q}(\text{x}_i)=\color{blue}{c_k}\text{ for some }k.\end{align*}\]
\[\color{red}{\text{WSS}}(\color{red}{q})=\sum_{i=1}^n\ell(\text{x}_i,\color{red}{q}(\text{x}_i))=\sum_{i=1}^n\|\text{x}_i,\color{red}{q}(\text{x}_i)\|^2.\]
\[\color{red}{\text{WSS}}(\color{red}{q})=\sum_{i=1}^n\ell(\text{x}_i,\color{red}{q}(\text{x}_i))=\sum_{i=1}^n\|\text{x}_i,\color{red}{q}(\text{x}_i)\|^2.\]
Measures the proximity of points within each group.
For any number of cluster \(K\), \[\color{blue}{\text{TSS}}=\color{green}{\text{BSS}}+\color{red}{\text{WSS}},\] where

Lemma 1: Nearet Neighbor Condition [Linder, T. (2002)]
Given centroids \(\color{blue}{\cal C}\), let \(\color{red}{q}\) be any quantizer and \(\color{blue}{\hat{q}}\) be the quantizer that assigns any observation \(\text{x}_i\) to its closest code-vector (centroid of its Voronoi partition), i.e., \[\color{blue}{\hat{q}}(\text{x}_i)=\arg\min_{\color{blue}{c_k}\in\color{blue}{\cal C}}\|\text{x}_i-\color{blue}{c_k}\|^2\]
Then, one has \[\color{red}{\text{WSS}}(\color{blue}{\hat{q}})\leq \color{red}{\text{WSS}}(\color{red}{q}).\]
Lemma 2: Centroid Condition [Linder, T. (2002)]
Given a partition \(\color{green}{{\cal S}}=\{\color{green}{S_1},\dots,\color{green}{S_K}\}\), let \(\color{red}{q}\) be any quantizer and \(\color{blue}{\hat{q}}\) be the quantizer with Voronoi parition and codebook \(\hat{\color{blue}{\cal C}}=\{\color{blue}{\hat{c}_k}\}\) defined by \[\color{blue}{\hat{c}_k}=\frac{1}{|\color{green}{S_K}|}\sum_{\text{x}_i\in \color{green}{S_K}}\text{x}_i.\]
Then, one has \[\color{red}{\text{WSS}}(\color{blue}{\hat{q}})\leq \color{red}{\text{WSS}}(q).\]
Nearet Neighbor Condition: Given codebook \(\color{blue}{\cal C}=\{\color{blue}{c_k}\}\), we know how to assign \(\text{x}_i\mapsto \color{blue}{c_k}\) optimally, therefore find the best Voronoi parition.
Centroid Condition: Given a partition \(\color{green}{\cal S}=\{\color{green}{S_k}\}\), we know how to define an optimal codebook \(\color{blue}{\cal C}=\{\color{blue}{c_k}\}\).
for i = 1,...,n:
…. for k = 1,...,K: \[\text{Assign }\text{x}_i\to \color{green}{S_k}\text{ if }\|\text{x}_i-\color{green}{c_k}\|\leq \|\text{x}_i-c_j\|,\forall j\neq k.\]
\[\color{green}{c_k}=\frac{1}{|\color{green}{S_k}|}\sum_{\text{x}_i\in \color{green}{S_k}}\text{x}_i.\]
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, init='random', max_iter=7, n_init=1, random_state=12)
km = km.fit(df1)
fig_km = go.Figure(go.Scatter(x=df1[:,0], y=df1[:,1], name="Data", mode="markers",
marker=dict(color=[col1[str(j+1)] for j in km.labels_], size=7)))
fig_km.add_trace(go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1],
name="Centroid", mode="markers", marker=dict(color='black', size=15, symbol='star')))
fig_km.update_layout(width=500, height=480, title="KMeans Algorithm in Action")
fig_km.show()for i = 1,...,n:
…. for k = 1,...,K: \[\text{Assign }\text{x}_i\to \color{green}{S_k}\text{ if }\|\text{x}_i-\color{green}{c_k}\|\leq \|\text{x}_i-c_j\|,\forall j\neq k.\]
\[\color{green}{c_k}=\frac{1}{|\color{green}{S_k}|}\sum_{\text{x}_i\in \color{green}{S_k}}\text{x}_i.\]
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, init='random', max_iter=7, n_init=1, random_state=11)
km = km.fit(df1)
fig_km = go.Figure(go.Scatter(x=df1[:,0], y=df1[:,1], name="Data", mode="markers",
marker=dict(color=[col1[str(j+1)] for j in km.labels_], size=7)))
fig_km.add_trace(go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1],
name="Centroid", mode="markers", marker=dict(color='black', size=15, symbol='star')))
fig_km.update_layout(width=500, height=480, title="KMeans Algorithm in Action")
fig_km.show()KMeans of sklearn.cluster module:🔑 Perform KMeans algorithm n_init times with different random initializations, the best one (lowest WSS) is taken as the final result.
Q2: The main point is ‘HOW TO FIND A SUITABLE \(K\)’?

🔑 \(\color{red}{\text{WSS}}\) decreases as \(K\) increases:
wss = []
list_k = list(range(1,11))
for k in list_k:
km = KMeans(n_clusters = k, n_init=2)
km = km.fit(df1)
wss.append(km.inertia_)
data_wss = pd.DataFrame({
'K' : list_k,
'WSS': wss
})
fig6 = px.line(
data_wss, x="K", y="WSS",
markers="WSS",
title="WSS vs Number of cluster (K)")
fig6.add_trace(
go.Scatter(x=[4,4], y=[0,wss[3]],
line=dict(
color="red", dash="dash"),
name="Optimal K"))
fig6.update_layout(width=500, height=180)
fig6.show()from plotly.subplots import make_subplots
list_k = list(range(1, 11))
wss = []
models = {}
for k in list_k:
# random_state ensures centroids don't initialize randomly each run
km = KMeans(n_clusters=k, max_iter=100, n_init=2, random_state=42)
km = km.fit(df1)
wss.append(km.inertia_)
models[k] = km
# We will animate K from 2 to 8 (list_k[1:-2])
slider_k = list_k[1:-2]
k_init = slider_k[0] # Starting K (K=2)
km_init = models[k_init]
fig = make_subplots(
rows=2, cols=1,
row_heights=[0.6, 0.4],
subplot_titles=("KMeans with different K", "Elbow Curve (WSS)"),
vertical_spacing=0.2
)
# TRACE 0: Scatter plot points (Row 1)
fig.add_trace(
go.Scatter(x=df1[:,0], y=df1[:,1], mode='markers',
marker=dict(color=km_init.labels_, size=7, colorscale='Viridis'),
name='Data points'),
row=1, col=1
)
# TRACE 1: Centroids (Row 1)
fig.add_trace(
go.Scatter(x=km_init.cluster_centers_[:,0], y=km_init.cluster_centers_[:,1],
name="Centroids", mode="markers",
marker=dict(color='red', size=15, symbol='star')),
row=1, col=1
)
# TRACE 2: Static Elbow Line (Row 2)
fig.add_trace(
go.Scatter(x=list_k, y=wss, mode='lines+markers',
line=dict(color='blue'), name='WSS'),
row=2, col=1
)
# TRACE 3: Moving Red Dot for current K on Elbow curve (Row 2)
fig.add_trace(
go.Scatter(x=[k_init], y=[wss[k_init-1]], mode='markers',
marker=dict(
color='red', size=12,
symbol='circle-open',
line=dict(width=3)),
name='Current K'),
row=2, col=1
)
frames = []
for k in slider_k:
km = models[k]
# We update Traces 0, 1, and 3. Trace 2 (the WSS line) stays static.
frame = go.Frame(
data=[
# Update Trace 0 (Scatter Colors)
go.Scatter(marker=dict(color=km.labels_, size=7, colorscale='Viridis')),
# Update Trace 1 (Centroids)
go.Scatter(x=km.cluster_centers_[:,0], y=km.cluster_centers_[:,1]),
# Update Trace 3 (Red dot on Elbow)
go.Scatter(x=[k], y=[wss[k-1]], marker=dict(
color=['green' if k==4 else 'red'][0],
size = [15 if k==4 else 12][0]))
],
name=str(k),
traces=[0, 1, 3] # This tells Plotly exactly which traces to update
)
frames.append(frame)
fig.frames = frames
animation_settings = {"frame": {"duration": 600, "redraw": True}, "mode": "immediate", "transition": {"duration": 0}}
fig.update_layout(
width=400, height=450,
showlegend=False,
updatemenus=[{
"buttons": [
{
"args": [None, animation_settings],
"label": "Play",
"method": "animate"
},
{
"args": [[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate"}],
"label": "Stop",
"method": "animate"
}
],
"type": "buttons",
"showactive": False,
"x": 0, "y": 1.1,
"pad": {"r": 10, "t": 10}
}],
sliders=[{
"active": 0,
"currentvalue": {"prefix": "K: "},
"pad": {"t": 20},
"steps": [{
"label": str(k),
"method": "animate",
"args": [[str(k)], animation_settings]
} for k in slider_k]
}]
)
# Fix axis ranges so they don't jump around during animation
fig.update_xaxes(range=[df1[:,0].min()-2, df1[:,0].max()+2], row=1, col=1, title_text="X1")
fig.update_yaxes(range=[df1[:,1].min()-2, df1[:,1].max()+2], row=1, col=1, title_text="X2")
fig.update_xaxes(title_text="Number of clusters (K)", row=2, col=1)
fig.update_yaxes(title_text="WSS", row=2, col=1)
fig.show()from sklearn.metrics import silhouette_score, silhouette_samples
km = KMeans(n_clusters=4, max_iter=100, n_init=2)
km = KMeans(n_clusters=4, max_iter=100, n_init=2, random_state=42)
km = km.fit(df1)
clusters = km.labels_
silhouette_avg = silhouette_score(df1, clusters)
sample_silhouette_values = silhouette_samples(df1, clusters)
# 3. Plotly Silhouette Plot
fig = go.Figure()
y_lower = 10
# Lists to hold the positions and text for the Y-axis labels
y_tick_vals = []
y_tick_text = []
for k in range(km.n_clusters):
# Aggregate the silhouette scores for samples belonging to cluster k, and sort them
ith_cluster_silhouette_values = sample_silhouette_values[clusters == k]
ith_cluster_silhouette_values.sort()
size_cluster_k = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_k
# Generate the Y coordinates for this cluster
y_range = np.arange(y_lower, y_upper)
# Equivalent to ax1.fill_betweenx()
fig.add_trace(
go.Scatter(
x=ith_cluster_silhouette_values,
y=y_range,
mode='lines',
fill='tozerox', # Fills the area from the curve to the X=0 axis
name=f'Cluster {k+1}',
line=dict(width=0.5)
)
)
# Calculate the center of the cluster on the Y-axis to place the label
y_tick_vals.append(y_lower + 0.5 * size_cluster_k)
y_tick_text.append(str(k + 1))
# Compute the new y_lower for the next plot
y_lower = y_upper + 10
# Equivalent to ax1.axvline()
fig.add_trace(
go.Scatter(
x=[silhouette_avg] * 2,
y=[0, df1.shape[0]],
mode='lines',
name='Ave coef',
line=dict(width=1.5, color='red', dash='dash')
)
)
# Update layout
fig.update_layout(
title="Silhouette plot for 4 clusters",
xaxis_title="Silhouette coefficients",
yaxis_title="Cluster label",
width=270,
height=250,
showlegend=False
)
fig.show()sc_av = []
for k in range(2,10):
kmeans = KMeans(n_clusters=k, n_init=3)
clusters = kmeans.fit_predict(df1)
sc_av.append(silhouette_score(df1, clusters))
sc_df = pd.DataFrame({'k' : range(2, 10),
'Silhouette coef' : sc_av})
fig6 = px.line(data_frame=sc_df, x='k', y='Silhouette coef', markers='Silhouette Coef')
fig6.add_trace(go.Scatter(x=[4,4],y=[np.min(sc_av), np.max(sc_av)], line=dict(dash="dash"), name=r"$K^*$"))
fig6.update_layout(width=270, height=230, title = "Silhouette coef vs K")
fig6.show()KMeans involves two alternative processes:
The algorithm may get stuck if it started from a bad initialization. Increasing n_init may solves this problem.
A suitable number of cluster \(K\) may be estimated using:
Real-world data may require one to prioritize interpretable \(K\) over above criteria!
Agglomerative clustering
| Linkage | Formula |
|---|---|
| Single Linkage | \(d_{\text{SL}}(A, B) = \min \{ \|a, b\|^2 : a \in A, b \in B \}\) |
| Complete Linkage | \(d_{\text{CoL}}(A, B) = \max \{ \|a, b\|^2 : a \in A, b \in B \}\) |
| Average Linkage | \(d_{\text{AL}}(A, B) = \frac{1}{|A||B|} \sum_{a \in A} \sum_{b \in B} \|a, b\|^2\) |
| Centroid Linkage | \(d_{\text{CeL}}(A, B) = \|\bar{a}, \bar{b}\|^2\) where \(\bar{a}\) and \(\bar{b}\) are centroids of clusters \(A\) and \(B\), respectively. |
| Ward’s Linkage | \(d_{\text{WL}}(A, B) = \sqrt{\frac{|A||B|}{|A| + |B|} \| \bar{a} - \bar{b} \|^2}\) |

from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.cluster import AgglomerativeClustering
import seaborn as sns
import numpy as np
import plotly.figure_factory as ff
# 2. Define our iteration parameters
methods = ['single', 'complete', 'average', 'ward']
ks = [3, 4, 5, 6]
titles = [
"Single Linkage", "Complete Linkage", "Average Linkage", "Ward's Linkage",
"K = 3", "K = 4", "K = 5", "K = 6"
]
# 3. Create the 2x4 Subplot Grid
fig = make_subplots(
rows=2, cols=4,
subplot_titles=titles,
vertical_spacing=0.15,
horizontal_spacing=0.05
)
# 4. Loop through the methods and Ks to populate the grid
for i, (method, k) in enumerate(zip(methods, ks)):
col = i + 1 # Plotly columns are 1-indexed
# Create a standalone dendrogram figure
dendro_fig = ff.create_dendrogram(
df1,
linkagefun=lambda x: linkage(x, method=method)
)
# Extract the line traces from the standalone figure and add them to our subplot
for trace in dendro_fig.data:
trace.showlegend = False
fig.add_trace(trace, row=1, col=col)
# Hide the X-axis ticks (mimics axs[0,c].set_xticks([]))
fig.update_xaxes(showticklabels=False, row=1, col=col)
clust = AgglomerativeClustering(n_clusters=k).fit_predict(df1)
scatter_trace = go.Scatter(
x=df1[:, 0],
y=df1[:, 1],
mode='markers',
marker=dict(
color=clust,
colorscale='Rainbow', # discrete-like continuous scale
size=7,
line=dict(width=0.5, color='white')
),
showlegend=False
)
fig.add_trace(scatter_trace, row=2, col=col)
# 5. Update Layout for a clean look
fig.update_layout(
height=400,
width=950,
plot_bgcolor='rgba(0,0,0,0)', # Transparent background
showlegend=False
)
# Add grids to scatter plots for better readability
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='lightgray', row=2)
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='lightgray', row=2)
fig.show()KMeans and Hierarchical clustering algorithms often struggle with non-convex cluster structures.np.random.seed(0)
theta = np.linspace(0, 2*np.pi, 100)
r1 = 1 + 0.2 * np.sin(4 * theta)
r2 = 2 + 0.2 * np.sin(4 * theta)
r3 = 0.5 * np.linspace(0.1, 5, 100)
x1 = r1 *np.cos(theta) - 3
y1 = r1 * np.sin(theta) # + np.random.normal(0, 0.3, 100)
x2 = r2 * np.cos(theta) - 3
y2 = r2 * np.sin(theta) #+ np.random.normal(0, 0.3, 100)
x3 = r3 * np.cos(theta) + 3.25
y3 = r3 * np.sin(theta) #+ np.random.normal(0, 0.3, 100)
x4 = r3 * np.cos(theta - np.pi) + 2.75
y4 = r3 * np.sin(theta - np.pi) #+ np.random.normal(0, 0.3, 100)
data = np.vstack((np.concatenate([x1, x2, x3, x4]), np.concatenate([y1, y2, y3, y4]))).T
# Create a DataFrame
df = pd.DataFrame(data, columns=['x', 'y'])
df['cluster'] = ['A'] * 100 + ['B'] * 100 + ['C'] * 100 + ['D'] * 100
# Plot using Plotly
fig = px.scatter(df, x='x', y='y', title='Data with Non-Convex Clusters')
fig.update_layout(width=450, height=220)
fig.show()# Kmeans
km1 = KMeans(n_clusters=4)
km1 = km1.fit(data)
# Hierarchical
Agg_clust = AgglomerativeClustering(n_clusters=4).fit_predict(data)
from plotly.subplots import make_subplots
fig7 = make_subplots(rows=2, cols=1, subplot_titles=("KMeans clustering", "Hierarchical clustering"))
fig7.add_trace(
go.Scatter(x=df['x'], y=df['y'], mode="markers",
marker=dict(color=km1.labels_), showlegend=False),
row=1, col=1
)
fig7.add_trace(
go.Scatter(x=df['x'], y=df['y'], mode="markers",
marker=dict(color=Agg_clust), showlegend=False),
row=2, col=1
)
fig7.update_layout(height=450, width=450)
fig7.show()KMeans and Hierarchical clustering algorithms often struggle with non-convex cluster structures.from sklearn.cluster import SpectralClustering
from sklearn.metrics import pairwise_kernels
def gaussian_similarity(X, sigma):
return pairwise_kernels(data, metric='rbf', gamma=1/(2*sigma**2))
sigma = 0.7
affinity_matrix = gaussian_similarity(data, sigma)
# Spectral Clustering
sc = SpectralClustering(n_clusters=4,
affinity="nearest_neighbors",
eigen_solver="arpack",
assign_labels='discretize')
labels = sc.fit_predict(affinity_matrix)
fig8 = go.Figure(go.Scatter(x=df['x'], y=df['y'], mode="markers",
marker=dict(color=labels), showlegend=False))
fig8.update_layout(height=200, width=450, title="Spectral Clustering")
fig8.show()Q3: How and why does it work?
A3: It relies on Laplacian of Graph Theory: rearranges and pulls strongly connected points into tighter and denser groups.
Read: Luxburg (2007)
\[W=\begin{bmatrix} & A & B & \dots & G \\ A & w_{11} & w_{12} & \dots & w_{17} \\ B & w_{21} & w_{22} & \vdots & w_{27} \\ \vdots & \vdots &\vdots &\ddots &\vdots\\ G & w_{71} & w_{72} & \dots & w_{77} \end{bmatrix} \]

\(W\) is called adjacency matrix of the graph \({\cal G}=\{W, E\}\) where \(E=\{A,B,...,G\}\).
Degree of node \(i\)-th: \(d_i=\sum_{ij}^nw_{ij}\).
Degree matrix: \(D=\text{diag}(d_1,\dots,d_n)\).
Number of connected components [Wang (2016)]
Let \(\cal G\) be an undirected graph with non-negative weights. Then the multiplicity \(k\) of the eigenvalue \(0\) of both \(L_{\text{rw}}\) and \(L_{\text{sym}}\) equals to the number of connected components \(G_1,...,G_k\) in the graph.
\[L=\begin{bmatrix} [L_1] & 0 & 0 & \dots & 0 \\ 0 & [L_2] & 0 & \dots & 0 \\ 0 & 0 & 0 & \ddots & 0\\ 0 & 0 & 0 & \dots & [L_k] \end{bmatrix}.\]
Algorithm [Wang (2016)]
KMeans clustering on \(U\) to obtain clusters: \(C_1,\dots,C_K\).image_gray = image[:,:,1].reshape(-1,1)
_, ax = plt.subplots(2, 2, figsize=(6, 4.2))
for k in range(2, 6):
km_image = KMeans(n_clusters=k)
km_image_fit = km_image.fit(image_gray)
image_compressed = np.array([np.mean(image_gray[km_image_fit.labels_==i]) for i in range(k)])
image_seg = np.zeros_like(km_image_fit.labels_)
for i in range(k):
image_seg[km_image_fit.labels_ == i] = image_compressed[i]
image_reshaped = image_seg.reshape(image.shape[0], image.shape[1])
ax[(k-2)//2,(k-2)%2].imshow(image_reshaped, cmap='gray')
ax[(k-2)//2,(k-2)%2].set_title(f"K = {k}")
ax[(k-2)//2,(k-2)%2].axis('off')
plt.axis('off')
plt.tight_layout()
plt.show()

Source: Ilanthiraiyan et al. (2014)

Source: Singh et al. (2020)
| Gender | Age | Annual Income (k$) | Spending Score (1-100) | |
|---|---|---|---|---|
| 0 | Male | 19 | 15 | 39 |
| 1 | Male | 21 | 15 | 81 |
| 2 | Female | 20 | 16 | 6 |
| 3 | Female | 23 | 16 | 77 |
| 4 | Female | 31 | 17 | 40 |
Q4: What should you do in preprocessing step?
A4: Exclude Gender, remove missing, duplicated values, scaling…
Missing values:
Gender Age Annual Income (k$) Spending Score (1-100)
0 0 0 0 0
column_colors = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA']
titles = [va if i == 0 else "" for i in range(4) for va in data.columns]
fig = make_subplots(
rows=4,
cols=4,
subplot_titles=titles,
vertical_spacing=0.08,
horizontal_spacing=0.05
)
for i in range(opt_k):
cluster_mask = km_opt.labels_ == i
for j, va in enumerate(data.columns):
row = i + 1
col = j + 1
subset = data.loc[cluster_mask, va]
current_color = column_colors[j % len(column_colors)]
if va == "Gender":
prop = subset.value_counts(normalize=True)
trace = go.Bar(
x=prop.index,
y=prop.values,
text=prop.values,
marker_color=current_color,
texttemplate="%{text:.2f}",
textposition="outside",
showlegend=False)
else:
mean_val = subset.median()
fig.add_shape(
type="line",
x0=mean_val, x1=mean_val,
y0=0, y1=1,
yref="y domain",
row=row, col=col,
line=dict(color="black", width=2, dash="dash"))
trace = go.Histogram(
x=subset,
marker_color=current_color,
showlegend=False)
fig.add_trace(trace, row=row, col=col)
if j == 0:
fig.update_yaxes(title_text=f'Cluster {i+1}', row=row, col=col)
fig.update_layout(
height=450,
width=900,
plot_bgcolor='white'
)
fig.update_xaxes(showline=True, linewidth=1, linecolor='black')
fig.update_yaxes(showline=True, linewidth=1, linecolor='black')
fig.show()titles = [va if i == 0 else "" for i in range(4) for va in data.columns]
fig = make_subplots(
rows=4,
cols=4,
subplot_titles=titles,
vertical_spacing=0.08,
horizontal_spacing=0.05
)
for i in range(opt_k):
cluster_mask = km_opt.labels_ == i
for j, va in enumerate(data.columns):
row = i + 1
col = j + 1
current_color = column_colors[j % len(column_colors)]
subset = data.loc[cluster_mask, va]
if va == "Gender":
prop = subset.value_counts(normalize=True)
trace = go.Bar(
x=prop.index,
y=prop.values,
text=prop.values,
marker_color=current_color,
texttemplate="%{text:.2f}",
textposition="outside",
showlegend=False)
else:
mean_val = subset.median()
fig.add_shape(
type="line",
x0=mean_val, x1=mean_val,
y0=0, y1=1,
yref="y domain",
row=row, col=col,
line=dict(color="black", width=2, dash="dash"))
trace = go.Histogram(
x=subset,
marker_color=current_color,
showlegend=False)
fig.add_trace(trace, row=row, col=col)
if j > 0:
fig.update_xaxes(
range=[np.min(data[va]), np.max(data[va])],
row=row, col=col)
if j == 0:
fig.update_yaxes(title_text=f'Cluster {i+1}', row=row, col=col)
fig.update_layout(
height=450,
width=900,
plot_bgcolor='white'
)
# Apply a clean grid and axes borders to match seaborn's default style
fig.update_xaxes(showline=True, linewidth=1, linecolor='black')
fig.update_yaxes(showline=True, linewidth=1, linecolor='black')
fig.show()
