The user wants a Python application to visualize network graphs using NetworkX.
I need to provide a complete, runnable, and well-explained example.
The application should be more than just a simple script; it should be something that feels like an "application" or at least a robust tool for visualization.
Key Components Needed:
Library:networkx is the core. I'll need matplotlib for the standard static visualization and potentially pyvis for an interactive HTML version, as that's often what people actually want when they say "visualize" (interactive is better for exploration).
Data: I need a sample graph. I can generate a random graph (like a Barabási-Albert or Erdős-Rényi graph) or create a custom small one manually. A random graph is better for showing layout capabilities.
Visualization Styles:
Basic: Matplotlib (good for quick checks, papers).
Interactive: Pyvis (good for exploration, sharing).
Features to demonstrate:
Adding nodes/edges.
Setting attributes (color, size, labels).
Layout algorithms (spring, circular, etc.).
Drawing.
Plan:
Introduction: Briefly explain what NetworkX is and the prerequisites (installing libraries).
Visualizer 2 (Pyvis - Optional but recommended): Actually, to keep dependencies low, I will focus on Matplotlib first, but mention Pyvis. Self-correction: The prompt asks for an "Application". A purely static image is a bit boring. I will implement a Matplotlib version that looks nice (customized) and includes code for interactive HTML using pyvis as an "bonus" extension because it's so popular for NetworkX.
Refining the "Application":
Let's create a class-based structure or a well-structured script.
Let's simulate a "Social Network" scenario.
Generate random data (Barabasi-Albert graph is good for "hubs").
Calculate centrality.
Visualizing: Use nx.spring_layout. Draw edges, nodes (with colormap), labels.
Add a legend/colorbar.
Advanced (Interactive): Show how to export to pyvis if they want interactive graphs (this adds significant value).
Let's stick to the Matplotlib implementation as the primary answer because it requires the fewest external dependencies (standard stack). I will add the interactive part as a "Next Step" because it requires pyvis.
Specifics for the Matplotlib visual:
Make it look modern.
Use a color map (e.g., 'viridis' or 'plasma').
Size nodes by degree.
Width edges by weight.
Let's write the actual code mentally:
python
import networkx as nx
import matplotlib.pyplot as plt
import random
# 1. Setup
G = nx.barabasi_albert_graph(50, 3) # 50 nodes, preferential attachment
# 2. Attributes
for node in G.nodes():
G.nodes[node]['group'] = random.choice(['A', 'B', 'C'])
G.nodes[node]['size'] = G.degree(node) * 10
# 3. Layout
pos = nx.spring_layout(G, seed=42)
# 4. Draw
# Extract attributes for plotting
node_colors = [G.degree(n) for n in G.nodes()]
node_sizes = [G.degree(n) * 100 for n in G.nodes()]
# Draw
nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=node_sizes, cmap=plt.cm.viridis)
nx.draw_networkx_edges(G, pos, alpha=0.4)
nx.draw_networkx_labels(G, pos, font_size=8)
plt.show()
This is good. I will polish this into a full tutorial format. I'll organize it into:
Prerequisites.
The Basic Plot.
The "Professional" Plot (customized with colors/sizes).
The Interactive Plot (using Pyvis).
This covers the spectrum from beginner to "I need this for a dashboard".
Final check of the prompt: "Develop a Python application". The output should be code. I will provide a complete script that acts as a "Network Visualizer".
I will write a script that:
Generates a random network (simulating a social network).
Analyzes it (finds important nodes).
Visualizes it statically (Matplotlib).
(Bonus) Visualizes it interactively (Pyvis).
This provides a complete solution. I will ensure the code is clean, commented, and PEP8 compliant.
Dependencies to mention:
pip install networkx matplotlib numpy
(plus pyvis for the bonus section).
Let's structure the response now.
Here is a complete guide to creating a Python application for visualizing network graphs.
I have provided two approaches:
Static Visualization (Matplotlib): Best for quick analysis, exporting images, and integration into reports.
Interactive Visualization (PyVis): Best for exploration, web dashboards, and presenting to non-technical users (nodes are draggable).
Prerequisites
You will need to install the necessary libraries. Run this in your terminal:
bash
pip install networkx matplotlib pyvis numpy
Approach 1: The "Professional" Static Graph (Matplotlib)
This script generates a random "Social Network" graph. It calculates which nodes are most important (Centrality), sizes them accordingly, and color-codes "communities" within the network.
python
import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np
def create_advanced_visualization():
# 1. Generate a Random Graph (Barabási–Albert preferential attachment model)
# This mimics real-world networks like the internet or social circles
G = nx.barabasi_albert_graph(n=50, m=3, seed=42)
# 2. Calculate Metrics
# Degree Centrality: Importance based on number of connections
centrality = nx.degree_centrality(G)
# Detect Communities (using the greedy modularity algorithm)
# This groups nodes that are densely connected to each other
communities = nx.community.greedy_modularity_communities(G)
# Create a dictionary mapping node -> community index
community_map = {}
for i, comm in enumerate(communities):
for node in comm:
community_map[node] = i
# 3. Prepare Visual Attributes
# Node Size based on centrality (more connections = bigger node)
node_sizes = [v * 1500 for v in centrality.values()]
# Node Color based on community
# We generate a color for each community found
colors = plt.cm.viridis(np.linspace(0, 1, len(communities)))
node_colors = [colors[community_map[node]] for node in G.nodes()]
# 4. Visualization Setup
plt.figure(figsize=(12, 10))
# Determine Layout (Spring layout is standard for force-directed graphs)
# k adjusts the distance between nodes
pos = nx.spring_layout(G, k=0.15, iterations=50, seed=42)
# Draw the Network
# nodes
nx.draw_networkx_nodes(
G, pos,
node_size=node_sizes,
node_color=node_colors,
alpha=0.8
)
# edges
nx.draw_networkx_edges(G, pos, alpha=0.3, edge_color="gray")
# labels
nx.draw_networkx_labels(G, pos, font_size=8, font_family="sans-serif")
# 5. Final Polish
plt.title("Network Analysis: Size by Centrality, Color by Community")
plt.axis("off") # Turn off x/y axis lines
plt.tight_layout()
plt.show()
if __name__ == "__main__":
create_advanced_visualization()
Approach 2: The Interactive Web Graph (PyVis)
Static images are hard to read for large graphs. pyvis creates a standalone HTML file where you can drag nodes, zoom, and hover over them to see details.
python
from pyvis.network import Network
import networkx as nx
import random
def create_interactive_graph():
# 1. Create a random graph
G = nx.barabasi_albert_graph(n=60, m=2, seed=42)
# 2. Add attributes to the graph nodes
# These will show up when you hover over a node in the browser
for node in G.nodes():
G.nodes[node]['title'] = f"Node {node}\nConnections: {G.degree(node)}"
G.nodes[node]['size'] = G.degree(node) * 3 # PyVis scales size differently
# 3. Initialize PyVis Network
# height/width: 100% of browser window
# bgcolor: background color
# font_color: text color
net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white")
# 4. Convert NetworkX graph to PyVis
# from_nx automatically handles the conversion
net.from_nx(G)
# 5. Physics Layout Settings
# 'barnes_hut' allows the graph to stabilize like planets in gravity
net.barnes_hut(gravity=-2000, central_gravity=0.3, spring_length=100)
# 6. Save and Show
net.show("my_network.html")
print("Graph generated: open 'my_network.html' in your browser.")
if __name__ == "__main__":
create_interactive_graph()
Summary of Concepts used:
The Graph (G): The data structure holding nodes (points) and edges (lines).
Layout (nx.spring_layout): An algorithm that simulates forces (like magnets or springs) to position nodes so they don't overlap. NetworkX calculates the X,Y coordinates; Matplotlib draws them.
Centrality: Used here to determine node size. A node with 10 connections is drawn larger than a node with 1 connection.
Communities: Used to determine color. Groups of nodes that connect mostly to each other are colored the same.