I'm currently focused on the overarching goal: building a Python app for visualizing network graphs using NetworkX. I'm prioritizing grasping the user experience, deciding on core features, and designing the basic framework. I'm mapping out the user interface design to ensure it's intuitive and effectively presents network data.
Examining Core Dependencies
I'm now diving into the specifics of the dependencies. It seems networkx is crucial for graph manipulation and the standard backend, matplotlib, for NetworkX plotting, is an option, as is plotly/pyvis for interactive graphs. I'm also considering the user interface. While a script is a quick start, streamlit looks attractive for its web-based approach. I've also outlined core features like graph creation, visualization, layout options, and customization, thinking these are the minimum viable elements.
Deciding the Presentation
I've determined that offering two approaches is best: a basic Matplotlib example for quick scripts and a more advanced Streamlit + PyVis interactive application. I'm focusing now on building out the Streamlit application as the primary solution. I'm prioritizing user interaction and data visualization. I believe this will provide the most complete solution.
Defining the Interface
I'm now structuring the Streamlit application. I've broken it down into imports, configurations, the sidebar controls, graph generation, plotting, and stats display. I'm focusing on the user controls, including node number, edge probability, layout choices, and color selection. I've decided to use a random graph generator for initial ease, but also included CSV upload. I'm sticking with Matplotlib for simplicity and control.
Improving the Visuals
I'm currently polishing the Matplotlib output, adding node labels and a basic degree centrality metric display. I'm also working to make the interface look professional and user-friendly. I will include a clear explanation of how to run the app, including prerequisites, and the complete source code, to aid end users.
Outlining the Structure
Now I'm focusing on the final touches, refining the documentation and ensuring that the application fully aligns with the original request. I've broken down the code, ensuring the components are well-explained. I'm also preparing for future enhancements, like CSV upload. Reviewing the overall project, I confirm it successfully visualizes network graphs, is a functional Streamlit application, and leverages NetworkX.
To develop a robust Python application for visualizing NetworkX graphs, the modern standard is to build an interactive web application.
While you can use matplotlib for static scripts, using Streamlit allows you to create a UI where you can adjust graph parameters in real-time.
Here is a complete guide to building an interactive Network Graph Visualizer.
Create a file named graph_app.py and copy the following code into it. This application allows you to generate random graphs, change layouts, and calculate network statistics.
python
How to run the application
Open your terminal/command prompt.
Navigate to the folder where you saved graph_app.py.
Run the following command:
bash
streamlit run graph_app.py
This will launch a local web server and open the application in your default browser (usually at http://localhost:8501).
Features of this Application
Dynamic Graph Generation:
Random (Erdos-Renyi): Good for simulating randomized connections.
Small World (Watts-Strogatz): Simulates social networks ("six degrees of separation").
Scale-Free (Barabasi-Albert): Simulates real-world networks like the internet or citation networks where "hubs" exist.
Interactive Visualization:
Change the layout algorithm (Spring, Circular, etc.) instantly to see which one reveals the structure of your data best.
Customize colors and sizes to fit your aesthetic needs.
Live Analytics:
It calculates Density (how saturated the graph is with edges).
It checks for Connectivity (can you reach every node from every other node?).
It calculates Degree Centrality to identify the most important nodes (Hubs).
Data Export:
Allows you to download the graph data as an Adjacency Matrix (CSV) for use in Excel or other tools.
Extending the Application
If you want to take this further, here are two advanced additions you can make:
1. Import your own Data:
You can add a file uploader using st.file_uploader to let users upload a CSV containing "Source" and "Target" columns, then use nx.from_pandas_edgelist to generate the graph.
2. Interactive Physics (Draggable Nodes):
Currently, the plot is static (an image). To make nodes draggable, you can integrate the pyvis library.
Install: pip install pyvis
Code tweak: Use pyvis.network.Network to generate an HTML file and render it using st.components.v1.html.
import streamlit as st
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# --- Page Config ---
st.set_page_config(page_title="NetworkX Visualizer", layout="wide")
st.title("🕸️ Interactive Network Graph Visualizer")
st.markdown("Generate different types of graphs, apply layouts, and analyze connectivity.")
# --- Sidebar Controls ---
st.sidebar.header("Graph Settings")
# 1. Graph Type Selection
graph_type = st.sidebar.selectbox(
"Select Graph Type",
("Random (Erdos-Renyi)", "Watts-Strogatz (Small World)", "Barabasi-Albert (Scale-Free)")
)
# 2. Node and Edge parameters based on Selection
num_nodes = st.sidebar.slider("Number of Nodes (N)", min_value=5, max_value=100, value=20)
if graph_type == "Random (Erdos-Renyi)":
edge_prob = st.sidebar.slider("Edge Probability (p)", 0.0, 1.0, 0.2)
G = nx.erdos_renyi_graph(num_nodes, edge_prob)
elif graph_type == "Watts-Strogatz (Small World)":
k_neighbors = st.sidebar.slider("K Nearest Neighbors", 2, 10, 4)
rewire_prob = st.sidebar.slider("Rewiring Probability (p)", 0.0, 1.0, 0.3)
# K must be smaller than N
if k_neighbors >= num_nodes:
k_neighbors = num_nodes - 1
G = nx.watts_strogatz_graph(num_nodes, k_neighbors, rewire_prob)
elif graph_type == "Barabasi-Albert (Scale-Free)":
m_attachments = st.sidebar.slider("Number of attachments (m)", 1, 10, 2)
if m_attachments >= num_nodes:
m_attachments = num_nodes - 1
G = nx.barabasi_albert_graph(num_nodes, m_attachments)
# 3. Visual Settings
st.sidebar.header("Visual Settings")
layout_option = st.sidebar.selectbox("Layout Algorithm", ["Spring", "Circular", "Kamada-Kawai", "Shell", "Random"])
node_color = st.sidebar.color_picker("Node Color", "#1f78b4")
node_size = st.sidebar.slider("Node Size", 100, 1000, 300)
show_labels = st.sidebar.checkbox("Show Labels", True)
# --- Main Visualizer Logic ---
col1, col2 = st.columns([3, 1])
with col1:
st.subheader("Graph Visualization")
# Create figure
fig, ax = plt.subplots(figsize=(10, 7))
# 1. Apply Layout
if layout_option == "Spring":
pos = nx.spring_layout(G, seed=42)
elif layout_option == "Circular":
pos = nx.circular_layout(G)
elif layout_option == "Kamada-Kawai":
pos = nx.kamada_kawai_layout(G)
elif layout_option == "Shell":
pos = nx.shell_layout(G)
else:
pos = nx.random_layout(G)
# 2. Draw Graph
nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color=node_color, alpha=0.9, ax=ax)
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, edge_color="gray", ax=ax)
if show_labels:
nx.draw_networkx_labels(G, pos, font_size=10, font_color="black", ax=ax)
# Remove axis formatting
ax.axis('off')
# Display in Streamlit
st.pyplot(fig)
# --- Statistics Panel ---
with col2:
st.subheader("Network Analysis")
num_edges = G.number_of_edges()
density = nx.density(G)
is_connected = nx.is_connected(G)
st.metric("Nodes", num_nodes)
st.metric("Edges", num_edges)
st.metric("Density", f"{density:.4f}")
st.write(f"**Connected:** {is_connected}")
if num_nodes > 0:
# Degree Centrality Top 5
st.markdown("### Top Nodes (Degree)")
degree_dict = dict(G.degree(G.nodes()))
# Sort by degree
sorted_degree = sorted(degree_dict.items(), key=lambda item: item[1], reverse=True)[:5]
for node, degree in sorted_degree:
st.text(f"Node {node}: {degree} connections")
# --- Export Option ---
st.sidebar.header("Export")
if st.sidebar.button("Download Adjacency Matrix"):
adj_df = nx.to_pandas_adjacency(G)
csv = adj_df.to_csv().encode('utf-8')
st.sidebar.download_button(
label="Click to Download CSV",
data=csv,
file_name='graph_adjacency_matrix.csv',
mime='text/csv',
)