1 import numpy as np 2 import matplotlib.pyplot as plt 3 from scipy.spatial import ConvexHull 4 from mpl_toolkits.mplot3d.art3d import Poly3DCollection 5 from _utils.plot_utils import setup_style, save_fig, PALETTE 6 setup_style() 7 8 np.random.seed(42) 9 classes = ['Class A', 'Class B', 'Class C'] 10 n_per = 80 11 all_pts, all_labels = [], [] 12 centers = [np.array([2, 2, 2]), np.array([-2, -1, 3]), np.array([0, -2, -1])] 13 for i, (cls, center) in enumerate(zip(classes, centers)): 14 pts = center + np.random.randn(n_per, 3) * 0.7 15 all_pts.append(pts) 16 all_labels.extend([cls] * n_per) 17 all_pts_arr = np.vstack(all_pts) 18 19 fig = plt.figure(figsize=(8, 7)) 20 ax = fig.add_subplot(111, projection='3d') 21 22 for i, (cls, pts) in enumerate(zip(classes, all_pts)): 23 # Scatter points 24 ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], s=12, alpha=0.4, 25 color=PALETTE[i], label=cls, edgecolor='none') 26 27 # Semi-transparent convex hull 28 try: 29 hull = ConvexHull(pts) 30 faces = [] 31 for simplex in hull.simplices: 32 face = [pts[s] for s in simplex] 33 faces.append(face) 34 poly = Poly3DCollection(faces, alpha=0.08, facecolor=PALETTE[i], 35 edgecolor=PALETTE[i], linewidth=0.3) 36 ax.add_collection3d(poly) 37 except Exception: 38 pass 39 40 # 2D projections on walls 41 # XY projection (on z wall) 42 z_wall = ax.get_zlim()[0] if hasattr(ax, '_zlim') else all_pts_arr[:, 2].min() - 2 43 ax.scatter(pts[:, 0], pts[:, 1], np.full(len(pts), all_pts_arr[:, 2].min() - 1.5), 44 s=3, alpha=0.1, color=PALETTE[i], edgecolor='none') 45 # XZ projection (on y wall) 46 ax.scatter(pts[:, 0], np.full(len(pts), all_pts_arr[:, 1].max() + 1.5), pts[:, 2], 47 s=3, alpha=0.1, color=PALETTE[i], edgecolor='none') 48 # YZ projection (on x wall) 49 ax.scatter(np.full(len(pts), all_pts_arr[:, 0].min() - 1.5), pts[:, 1], pts[:, 2], 50 s=3, alpha=0.1, color=PALETTE[i], edgecolor='none') 51 52 # Class center label 53 cx, cy, cz = pts.mean(axis=0) 54 ax.text(cx, cy, cz + 0.5, cls, fontsize=8, fontweight='bold', color=PALETTE[i], 55 ha='center', va='bottom') 56 57 ax.set_xlabel('Dim 1', fontsize=10, labelpad=6) 58 ax.set_ylabel('Dim 2', fontsize=10, labelpad=6) 59 ax.set_zlabel('Dim 3', fontsize=10, labelpad=6) 60 ax.view_init(elev=20, azim=135) 61 ax.tick_params(labelsize=8) 62 ax.legend(fontsize=9, markerscale=3) 63 fig.tight_layout() 64 save_fig(fig, 'figures/fig_3d_features.pdf')