Module 12. Social Network Analysis


 


Once I had the correct Python version installed, the code for building and visualizing the social network worked smoothly. Using NetworkX made it easy to generate the random graph structure, and Plotnine provided a clean, ggplot-style way to visualize the nodes and edges. The final plot rendered clearly, and saving it as a PNG was straightforward! The biggest issue I ran into was with package compatibility. My computer was using Python 3.13, but the Plotnine package is not supported on that version yet. Because of that, the install kept failing and the plotnine module couldn't be imported. I solved the problem by installing Python 3.11, which is fully compatible with Plotnine. After switching to Python 3.11 and reinstalling the required packages, everything ran correctly. Yes — I would definitely use this approach again. NetworkX and Plotnine work well together: NetworkX handles the graph structure, while Plotnine gives me fine control over the aesthetics. For simple social network visualizations, this method is clear, flexible, and produces clean results.















Code:

import networkx as nx
import pandas as pd
from plotnine import *
import matplotlib.pyplot as plt

# 1. Create a random undirected network with 10 nodes
G = nx.gnp_random_graph(10, 0.5)

# Assign labels A, B, C, ... to the nodes
labels = {i: chr(65 + i) for i in G.nodes()}
nx.set_node_attributes(G, labels, 'label')

# 2. Extract node positions using spring layout
pos = nx.spring_layout(G, seed=42)

# Create node DataFrame
nodes_df = pd.DataFrame({
'x': [pos[n][0] for n in G.nodes()],
'y': [pos[n][1] for n in G.nodes()],
'name': [G.nodes[n]['label'] for n in G.nodes()]
})

# Create edge DataFrame
edges_df = pd.DataFrame([
{'x': pos[u][0], 'y': pos[u][1], 'xend': pos[v][0], 'yend': pos[v][1]}
for u, v in G.edges()
])

# 3. Build the plot with plotnine
network_plot = (
ggplot() +
geom_segment(
data=edges_df,
mapping=aes(x='x', y='y', xend='xend', yend='yend'),
color="gray",
size=0.5
) +
geom_point(
data=nodes_df,
mapping=aes(x='x', y='y'),
color='black',
size=3
) +
geom_text(
data=nodes_df,
mapping=aes(x='x', y='y', label='name'),
nudge_y=0.03,
size=8,
color='darkblue'
) +
theme_void() +
ggtitle("Social Network Graph")
)

# Display the plot
print(network_plot)

# Save the plot
network_plot.save("social_network_graph.png", dpi=300)
print("Saved plot as social_network_graph.png")

Comments

Popular posts from this blog

Final Project Diamond Database

Module 6. basic data visualization using R

Module 5. Assignment: Create Your Own Visualizations assignment Plotly vs. Datawrapper