Social Network Analysis with NetworkX

Analyzing a social network graph to identify influential users and communities

Python
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict

# Create a sample social network
G = nx.Graph()
G.add_edges_from([
    ('Alice', 'Bob'), ('Alice', 'Charlie'), ('Bob', 'David'),
    ('Charlie', 'David'), ('Charlie', 'Eve'), ('David', 'Eve'),
    ('Eve', 'Frank'), ('Frank', 'George'), ('Frank', 'Helen'),
    ('George', 'Helen'), ('Helen', 'Ivan'), ('Ivan', 'Julia')
])

# Calculate and print degree centrality
degree_centrality = nx.degree_centrality(G)
print("Degree Centrality (Top 3 users):")
for user, centrality in sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:3]:
    print(f"{user}: {centrality:.3f}")

# Identify communities using the Louvain method
communities = nx.community.louvain_communities(G)
print("\nCommunities:")
for i, community in enumerate(communities, 1):
    print(f"Community {i}: {', '.join(community)}")

# Calculate and print betweenness centrality
betweenness_centrality = nx.betweenness_centrality(G)
print("\nBetweenness Centrality (Top 3 users):")
for user, centrality in sorted(betweenness_centrality.items(), key=lambda x: x[1], reverse=True)[:3]:
    print(f"{user}: {centrality:.3f}")

# Visualize the network
pos = nx.spring_layout(G)
plt.figure(figsize=(12, 8))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=500, font_size=10, font_weight='bold')

# Color communities
color_map = plt.cm.get_cmap('Set3')
for i, community in enumerate(communities):
    nx.draw_networkx_nodes(G, pos, nodelist=community, node_color=[color_map(i / len(communities))] * len(community), node_size=500)

plt.title("Social Network Graph with Communities")
plt.axis('off')
plt.tight_layout()
plt.show()
Click Run or press shift + ENTER to run code.