#!/usr/bin/env python3
"""
Network Graph Visualizer
========================
A interactive command-line Python application to create, manipulate, and visualize
network graphs using NetworkX and Matplotlib.
Features:
- Generate random graphs (Erdős–Rényi, Barabási–Albert)
- Manually add nodes and edges
- Compute various layouts (spring, circular, spectral, etc.)
- Visualize graphs with labels and customizable appearance
- Show basic graph statistics
- Supports undirected graphs (easy to extend to directed)
Installation:
-------------
pip install networkx matplotlib
Usage:
------
Save this code as `network_graph_viz.py` and run:
python network_graph_viz.py
Author: Sherlock (Trailblazer Labs)
"""
import networkx as nx
import matplotlib.pyplot as plt
class NetworkGraphVisualizer:
def __init__(self):
self.G = None
self.pos = None
def new_graph(self):
"""Create a new empty undirected graph."""
self.G = nx.Graph()
self.pos = None
print("New empty undirected graph created.")
def random_erdos_renyi(self):
"""Generate an Erdos-Renyi random graph."""
try:
n = int(input("Number of nodes: "))
p = float(input("Edge probability (0-1): "))
if not 0 <= p <= 1:
raise ValueError("p must be between 0 and 1")
self.G = nx.erdos_renyi_graph(n, p)
self.pos = None
print(f"Generated Erdos-Renyi graph: {n} nodes, p={p:.2f}")
except ValueError as e:
print(f"Error: {e}")
def random_barabasi(self):
"""Generate a Barabasi-Albert scale-free graph."""
try:
n = int(input("Number of nodes: "))
m = int(input("Edges per new node (1 <= m < n): "))
if m >= n or m < 1:
raise ValueError("m must be 1 <= m < n")
self.G = nx.barabasi_albert_graph(n, m)
self.pos = None
print(f"Generated Barabasi-Albert graph: {n} nodes, m={m}")
except ValueError as e:
print(f"Error: {e}")
def add_node(self):
"""Add a single node (label can be any hashable type, e.g., str/int)."""
if self.G is None:
self.new_graph()
node = input("Node label: ").strip()
if node:
self.G.add_node(node)
print(f"Added node '{node}'.")
else:
print("Empty label, node not added.")
def add_edge(self):
"""Add an undirected edge between two nodes."""
if self.G is None:
self.new_graph()
u = input("From node: ").strip()
v = input("To node: ").strip()
if u and v and u != v:
self.G.add_edge(u, v)
print(f"Added edge '{u}' -- '{v}'.")
else:
print("Invalid nodes, edge not added.")
def compute_layout(self):
"""Compute graph layout using specified algorithm."""
if self.G is None:
print("No graph loaded! Create one first.")
return
print("Available layouts: spring, circular, spectral, random, shell, fruchterman_reingold, kamada_kawai")
layout_name = input("Layout name: ").strip().lower()
layouts = {
'spring': nx.spring_layout,
'circular': nx.circular_layout,
'spectral': nx.spectral_layout,
'random': nx.random_layout,
'shell': nx.shell_layout,
'fruchterman_reingold': nx.fruchterman_reingold_layout,
'kamada_kawai': nx.kamada_kawai_layout,
}
if layout_name in layouts:
try:
self.pos = layouts[layout_name](self.G)
print(f"Computed '{layout_name}' layout.")
except Exception as e:
print(f"Layout computation failed: {e}")
else:
print("Unknown layout! Using spring layout.")
self.pos = nx.spring_layout(self.G)
def visualize(self):
"""Draw the graph using current layout."""
if self.G is None:
print("No graph loaded!")
return
if self.pos is None:
print("No layout computed! Computing spring layout...")
self.pos = nx.spring_layout(self.G)
plt.figure(figsize=(12, 8))
# Draw nodes with size proportional to degree, edges with alpha
degrees = dict(self.G.degree())
nx.draw(
self.G,
self.pos,
with_labels=True,
node_color='lightblue',
node_size=[degrees[node] * 100 + 300 for node in self.G.nodes()],
font_size=10,
font_weight='bold',
edge_color='gray',
alpha=0.7,
width=1.5
)
plt.title(f"Network Graph\n(Nodes: {self.G.number_of_nodes()}, Edges: {self.G.number_of_edges()})")
plt.axis('off')
plt.tight_layout()
plt.show()
def show_stats(self):
"""Display basic graph statistics."""
if self.G is None:
print("No graph loaded!")
return
print("\n=== Graph Statistics ===")
print(f"Nodes: {self.G.number_of_nodes()}")
print(f"Edges: {self.G.number_of_edges()}")
avg_degree = sum(d for n, d in self.G.degree()) / self.G.number_of_nodes()
print(f"Average degree: {avg_degree:.2f}")
print(f"Is connected: {nx.is_connected(self.G)}")
if len(self.G) > 0:
print(f"Clustering coefficient: {nx.average_clustering(self.G):.4f}")
print(f"Degree sequence (top 5): {sorted([d for n, d in self.G.degree()], reverse=True)[:5]}")
def run(self):
"""Main interactive loop."""
print("=== Network Graph Visualizer (NetworkX) ===")
print("Start by creating a new graph or generating a random one!")
while True:
print("\n" + "="*50)
print("Options:")
print(" 1. New empty graph")
print(" 2. Erdos-Renyi random graph")
print(" 3. Barabasi-Albert random graph")
print(" 4. Add node")
print(" 5. Add edge")
print(" 6. Compute layout")
print(" 7. Visualize graph")
print(" 8. Show statistics")
print(" 0. Quit")
choice = input("\nChoose option: ").strip()
if choice == '1':
self.new_graph()
elif choice == '2':
self.random_erdos_renyi()
elif choice == '3':
self.random_barabasi()
elif choice == '4':
self.add_node()
elif choice == '5':
self.add_edge()
elif choice == '6':
self.compute_layout()
elif choice == '7':
self.visualize()
elif choice == '8':
self.show_stats()
elif choice == '0':
print("Goodbye!")
break
else:
print("Invalid option! Try again.")
if __name__ == "__main__":
app = NetworkGraphVisualizer()
app.run()
Quick Start
- Install dependencies:
pip install networkx matplotlib
- Run the app:
python network_graph_viz.py
- Example workflow:
- Choose
2 → Enter 10 nodes, 0.3 probability → Random graph generated.
- Choose
6 → Enter spring → Layout computed.
- Choose
7 → Graph visualizes in a pop-up window.
- Choose
8 → See stats.
Extensions
- Save/Load: Add
nx.write_graphml(self.G, 'graph.graphml') and self.G = nx.read_graphml('graph.graphml').
- Directed graphs: Replace
nx.Graph() with nx.DiGraph() and adjust drawing (nx.draw_directed).
- Interactive web app: Integrate with Streamlit + PyVis for browser-based interactivity.
- Node/edge attributes: Extend
add_node/add_edge to set colors, weights, etc.
This app is modular, extensible, and production-ready for basic network visualization! 🚀