The user wants a Python application that visualizes network graphs using NetworkX. I think they'll appreciate example code and clear explanations but not too much detail. I’ll consider using Matplotlib for static visuals and maybe also touch on interactive options like Plotly or PyVis.
Key components to include are loading data, graph definition, and layout considerations. I should design it modularly, possibly with a command-line interface that accepts node/edge files and layout selections. This sounds like an exciting project!Structuring the graph visualization application
I’m thinking the application should be around 50-100 lines long. First, I’ll include installation instructions for dependencies like NetworkX and Matplotlib.
Then, I’ll create a script, "visualize_graph.py," that handles command-line arguments for input files, formats, layouts, and direct output options. It will read the graph using NetworkX, possibly expecting an edge list in CSV format.
I could also mention interactive options with Plotly or PyVis, but let’s keep the focus simple and concise with a well-structured overview, installation steps, the full code, usage examples, and suggestions for improvements.Defining best coding practices
I’ll include best practices by creating separate functions for building the graph, choosing the layout, and drawing the graph. It's important to ensure the code is self-contained and easy to follow, focusing on modularity. Instead of starting with phrases like "Great question," I’ll dive right into the content to keep the response direct and engaging.
Let’s keep it structured and organized to help the user understand the flow of the application! Below is a small but complete Python application that uses NetworkX to visualize network graphs from common input formats (edge list, GEXF, GML) with different layouts.
1. Requirements
bash
pip install networkx matplotlib
2. Application: visualize_graph.py
python
#!/usr/bin/env python3
"""
visualize_graph.py
A simple NetworkX-based graph viewer.
Examples:
# Edge list (u v) text file
python visualize_graph.py --input edges.txt --format edgelist --layout spring
# GEXF file
python visualize_graph.py --input graph.gexf --format gexf --layout kamada_kawai
# Save to PNG instead of showing interactively
python visualize_graph.py --input edges.txt --format edgelist --output graph.png
"""
import argparse
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import networkx as nx
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Visualize network graphs with NetworkX."
)
parser.add_argument(
"--input", "-i", required=True, type=str,
help="Path to the input graph file (edge list, GEXF, GML, etc.)."
)
parser.add_argument(
"--format", "-f", required=True, type=str, choices=["edgelist", "gexf", "gml"],
help="Input format: 'edgelist', 'gexf', or 'gml'."
)
parser.add_argument(
"--directed", "-d", action="store_true",
help="Treat the graph as directed."
)
parser.add_argument(
"--layout", "-l", type=str, default="spring",
choices=["spring", "circular", "kamada_kawai", "shell", "random"],
help="Layout algorithm to use."
)
parser.add_argument(
"--node-size", type=float, default=300,
help="Node size in the plot (default: 300)."
)
parser.add_argument(
"--node-color", type=str, default="skyblue",
help="Node color (matplotlib color spec, default: 'skyblue')."
)
parser.add_argument(
"--edge-color", type=str, default="gray",
help="Edge color (default: 'gray')."
)
parser.add_argument(
"--with-labels", action="store_true",
help="Draw node labels."
)
parser.add_argument(
"--output", "-o", type=str,
help="If provided, save the figure to this file instead of displaying."
)
parser.add_argument(
"--title", type=str, default="Network Graph",
help="Title for the plot window."
)
return parser.parse_args()
def load_graph(path: str, fmt: str, directed: bool) -> nx.Graph:
p = Path(path)
if not p.exists():
print(f"Error: File not found: {path}", file=sys.stderr)
sys.exit(1)
# Choose graph class
G_class = nx.DiGraph if directed else nx.Graph
if fmt == "edgelist":
# Assumes simple whitespace-separated "u v" or "u v weight"
G = nx.read_edgelist(p, create_using=G_class())
elif fmt == "gexf":
G = nx.read_gexf(p)
if directed and not isinstance(G, nx.DiGraph):
G = G.to_directed()
elif not directed and not isinstance(G, nx.Graph):
G = G.to_undirected()
elif fmt == "gml":
G = nx.read_gml(p)
if directed and not isinstance(G, nx.DiGraph):
G = G.to_directed()
elif not directed and not isinstance(G, nx.Graph):
G = G.to_undirected()
else:
print(f"Unsupported format: {fmt}", file=sys.stderr)
sys.exit(1)
return G
def compute_layout(G: nx.Graph, layout_name: str):
if layout_name == "spring":
return nx.spring_layout(G, seed=42)
elif layout_name == "circular":
return nx.circular_layout(G)
elif layout_name == "kamada_kawai":
return nx.kamada_kawai_layout(G)
elif layout_name == "shell":
return nx.shell_layout(G)
elif layout_name == "random":
return nx.random_layout(G, seed=42)
else:
# Fallback
return nx.spring_layout(G, seed=42)
def draw_graph(
G: nx.Graph,
layout_name: str,
node_size: float,
node_color: str,
edge_color: str,
with_labels: bool,
title: str,
output: str | None,
):
pos = compute_layout(G, layout_name)
plt.figure(figsize=(8, 6))
nx.draw(
G,
pos,
with_labels=with_labels,
node_size=node_size,
node_color=node_color,
edge_color=edge_color,
linewidths=0.5,
font_size=8,
arrows=isinstance(G, nx.DiGraph),
arrowsize=15,
)
plt.title(title)
plt.axis("off")
if output:
plt.tight_layout()
plt.savefig(output, dpi=300)
print(f"Saved graph visualization to {output}")
else:
plt.tight_layout()
plt.show()
def main():
args = parse_args()
G = load_graph(args.input, args.format, args.directed)
print(f"Loaded graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
draw_graph(
G=G,
layout_name=args.layout,
node_size=args.node_size,
node_color=args.node_color,
edge_color=args.edge_color,
with_labels=args.with_labels,
title=args.title,
output=args.output,
)
if __name__ == "__main__":
main()
If you want, I can extend this to an interactive web UI (e.g., using PyVis or Plotly Dash) or add support for weighted/colored edges based on attributes.