Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Created May 3, 2025 12:52
Show Gist options
  • Save koorukuroo/dabc7faf6bb6266ee8af5ad9f12bcfe0 to your computer and use it in GitHub Desktop.
Save koorukuroo/dabc7faf6bb6266ee8af5ad9f12bcfe0 to your computer and use it in GitHub Desktop.
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms.community import greedy_modularity_communities
import matplotlib.cm as cm
import numpy as np
# Load graph
G = nx.les_miserables_graph()
# Compute centrality
degree_centrality = nx.degree_centrality(G)
# Detect communities
communities = list(greedy_modularity_communities(G))
node_community_map = {}
for i, comm in enumerate(communities):
for name in comm:
node_community_map[name] = i
# Prepare layout
pos = nx.spring_layout(G, seed=42)
# Node color by community
cmap = cm.get_cmap('Set3', len(communities))
node_colors = [cmap(node_community_map[node]) for node in G.nodes()]
# Node size by centrality
node_sizes = [degree_centrality[node] * 3000 for node in G.nodes()]
# Edge width by weight
edge_weights = [G[u][v]['weight'] for u, v in G.edges()]
edge_widths = [w / 2 for w in edge_weights]
# Draw nodes
plt.figure(figsize=(14, 10))
nx.draw_networkx_nodes(G, pos,
node_size=node_sizes,
node_color=node_colors,
alpha=0.9)
# Draw edges
nx.draw_networkx_edges(G, pos,
width=edge_widths,
alpha=0.3)
# Draw labels for top central nodes only (optional)
top_nodes = sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:10]
labels = {name: name for name, _ in top_nodes}
nx.draw_networkx_labels(G, pos, labels, font_size=9, font_color='black')
# Title and background
plt.title('Les Misérables Character Network (Centrality & Community)', fontsize=16)
plt.axis('off')
plt.gca().set_facecolor('none')
plt.gcf().patch.set_alpha(0.0)
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment