1 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten; from _utils.vivid_config import palette_colors 2 setup_style(); scale_colors = palette_colors() 3 import matplotlib.pyplot as plt 4 import matplotlib.colors as mcolors 5 import numpy as np 6 7 try: 8 import networkx as nx 9 except ImportError: 10 import subprocess, sys 11 subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'networkx', '-q']) 12 import networkx as nx 13 14 from scipy.spatial import ConvexHull 15 16 G = nx.karate_club_graph() 17 communities = list(nx.community.greedy_modularity_communities(G)) 18 19 # Assign community colors 20 color_map = {} 21 for i, comm in enumerate(communities): 22 for node in comm: 23 color_map[node] = i 24 node_colors = [PALETTE[color_map[n] % len(PALETTE)] for n in G.nodes()] 25 26 # Node sizing by degree 27 degrees = dict(G.degree()) 28 max_deg = max(degrees.values()) 29 node_sizes = [400 * degrees[n] / max_deg + 80 for n in G.nodes()] 30 31 fig, ax = plt.subplots(figsize=(8, 7)) 32 pos = nx.spring_layout(G, seed=42, k=0.5) 33 34 # Draw convex hulls for communities 35 for i, comm in enumerate(communities): 36 if len(comm) >= 3: 37 points = np.array([pos[n] for n in comm]) 38 try: 39 hull = ConvexHull(points) 40 hull_points = points[hull.vertices] 41 # Close the polygon 42 hull_points = np.vstack([hull_points, hull_points[0]]) 43 # Expand hull slightly 44 centroid = points.mean(axis=0) 45 expanded = centroid + 1.15 * (hull_points - centroid) 46 ax.fill(expanded[:, 0], expanded[:, 1], 47 color=PALETTE[i % len(PALETTE)], alpha=0.08) 48 ax.plot(expanded[:, 0], expanded[:, 1], 49 color=PALETTE[i % len(PALETTE)], linewidth=1.5, 50 linestyle='--', alpha=0.4) 51 except Exception: 52 pass 53 54 # Edge weight gradient 55 edges = G.edges() 56 edge_weights = [G[u][v].get('weight', 1) for u, v in edges] 57 max_w = max(edge_weights) if edge_weights else 1 58 cmap_edge = mcolors.LinearSegmentedColormap.from_list('ew', [_lighten(scale_colors[0], 0.8), COLORS['ref_line']]) 59 for (u, v), w in zip(edges, edge_weights): 60 x0, y0 = pos[u] 61 x1, y1 = pos[v] 62 norm_w = w / max_w 63 ax.plot([x0, x1], [y0, y1], color=cmap_edge(norm_w), 64 linewidth=0.5 + 1.5 * norm_w, alpha=0.3 + 0.4 * norm_w, zorder=1) 65 66 # Draw nodes 67 nx.draw_networkx_nodes(G, pos, ax=ax, node_color=node_colors, node_size=node_sizes, 68 edgecolors='white', linewidths=1.2, alpha=0.9, zorder=3) 69 70 # Labels for high-degree nodes only 71 high_deg_nodes = {n: str(n) for n in G.nodes() if degrees[n] >= 4} 72 nx.draw_networkx_labels(G, pos, labels=high_deg_nodes, ax=ax, 73 font_size=7, font_color=COLORS['text'], font_weight='bold') 74 75 # Legend for communities 76 from matplotlib.lines import Line2D 77 legend_elements = [Line2D([0], [0], marker='o', color='w', 78 markerfacecolor=PALETTE[i % len(PALETTE)], 79 markersize=10, label=f'Community {i+1}') 80 for i in range(len(communities))] 81 ax.legend(handles=legend_elements, loc='upper left', frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=8, fancybox=True) 82 83 ax.set_axis_off() 84 fig.tight_layout() 85 save_fig(fig, 'figures/fig_network.pdf')