3D Scatter

K-Means Clustering (k=4)

3D visualization of K-means clustering with 4 distinct clusters and their centroids.

Output
K-Means Clustering (k=4)
Python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

# Generate 4 clusters
centers = [(-2, -2, -2), (2, 2, -2), (-2, 2, 2), (2, -2, 2)]
colors_cluster = ['#06b6d4', '#ec4899', '#22c55e', '#f59e0b']
n_per_cluster = 75

all_x, all_y, all_z, all_c = [], [], [], []

for i, (cx, cy, cz) in enumerate(centers):
    x = np.random.normal(cx, 0.6, n_per_cluster)
    y = np.random.normal(cy, 0.6, n_per_cluster)
    z = np.random.normal(cz, 0.6, n_per_cluster)
    all_x.extend(x)
    all_y.extend(y)
    all_z.extend(z)
    all_c.extend([colors_cluster[i]] * n_per_cluster)

fig = plt.figure(figsize=(10, 8), facecolor='#0a0a0f')
ax = fig.add_subplot(111, projection='3d', facecolor='#0a0a0f')

ax.scatter(all_x, all_y, all_z, c=all_c, s=30, alpha=0.7, edgecolors='none')

# Mark cluster centers
for i, (cx, cy, cz) in enumerate(centers):
    ax.scatter([cx], [cy], [cz], c='white', s=200, marker='*', edgecolors=colors_cluster[i], linewidths=2)

ax.set_xlabel('Feature 1', color='white', fontsize=10)
ax.set_ylabel('Feature 2', color='white', fontsize=10)
ax.set_zlabel('Feature 3', color='white', fontsize=10)
ax.set_title('K-Means Clustering (k=4)', color='white', fontsize=14, fontweight='bold', pad=20)

ax.tick_params(colors='#64748b', labelsize=8)
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
ax.xaxis.pane.set_edgecolor('#1e293b')
ax.yaxis.pane.set_edgecolor('#1e293b')
ax.zaxis.pane.set_edgecolor('#1e293b')

ax.view_init(elev=20, azim=45)
plt.tight_layout()
plt.show()
Library

Matplotlib

Category

3D Charts

Did this help you?

Support PyLucid to keep it free & growing

Support