Python - Visualize graphs generated in NetworkX using Matplotlib

NetworkX is a powerful Python library for creating, manipulating, and studying complex networks. When combined with Matplotlib, it provides excellent capabilities for visualizing graphs with customizable layouts, colors, and labels.

Basic Graph Visualization

The simplest way to visualize a NetworkX graph is using the draw() function with Matplotlib ?

import networkx as nx
import matplotlib.pyplot as plt

# Create a simple graph
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)

# Draw and display the graph
nx.draw(G, with_labels=True, node_color='lightblue', node_size=500)
plt.title("Basic Graph Visualization")
plt.show()

Visualizing Graphs with Node Labels and Edge Weights

For more complex visualizations, you can add custom labels and display edge weights ?

import networkx as nx
import matplotlib.pyplot as plt

# Create graph with labeled nodes and weighted edges
G = nx.Graph()

# Add nodes with labels
G.add_node(1, label='A')
G.add_node(2, label='B')
G.add_node(3, label='C')
G.add_node(4, label='D')

# Add weighted edges
G.add_edge(1, 2, weight=4)
G.add_edge(2, 3, weight=7)
G.add_edge(3, 1, weight=2)
G.add_edge(1, 4, weight=5)

# Set node positions
pos = nx.spring_layout(G)

# Draw nodes and edges
nx.draw_networkx_nodes(G, pos, node_color='lightcoral', node_size=1000)
nx.draw_networkx_edges(G, pos, edge_color='gray')

# Add node labels
node_labels = nx.get_node_attributes(G, 'label')
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=16)

# Add edge weight labels
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

plt.title("Graph with Node Labels and Edge Weights")
plt.axis('off')
plt.show()

Using Subplots for Multiple Graph Views

Subplots allow you to display multiple graph visualizations side by side ?

import networkx as nx
import matplotlib.pyplot as plt

# Create a path graph
G = nx.path_graph(5)

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Plot with default layout
ax1.set_title('Default Layout')
nx.draw(G, ax=ax1, with_labels=True, node_color='lightblue', node_size=500)

# Plot with spring layout and custom styling
ax2.set_title('Spring Layout with Custom Styling')
pos = nx.spring_layout(G)
nx.draw(G, pos=pos, ax=ax2, node_color='red', node_size=800, 
        with_labels=True, font_color='white', edge_color='blue')

plt.suptitle('Multiple Graph Visualizations')
plt.tight_layout()
plt.show()

Different Graph Types and Layouts

NetworkX supports various graph types and layout algorithms ?

import networkx as nx
import matplotlib.pyplot as plt

# Create different types of graphs
graphs = [
    ("Complete Graph", nx.complete_graph(5)),
    ("Star Graph", nx.star_graph(4)),
    ("Random Graph", nx.erdos_renyi_graph(6, 0.5))
]

fig, axes = plt.subplots(1, 3, figsize=(15, 5))

for i, (title, graph) in enumerate(graphs):
    axes[i].set_title(title)
    nx.draw(graph, ax=axes[i], with_labels=True, 
            node_color='lightgreen', node_size=600)
    axes[i].axis('off')

plt.tight_layout()
plt.show()

Saving Graph Visualizations

You can save your graph visualizations to various file formats ?

import networkx as nx
import matplotlib.pyplot as plt

# Create and visualize a graph
G = nx.cycle_graph(6)
pos = nx.circular_layout(G)

nx.draw(G, pos, with_labels=True, node_color='yellow', 
        node_size=1000, font_size=16, font_weight='bold')
plt.title("Circular Graph Layout")

# Save the graph as PNG file
plt.savefig('/tmp/network_graph.png', dpi=300, bbox_inches='tight')
plt.show()

print("Graph saved as network_graph.png")
Graph saved as network_graph.png

Key Visualization Parameters

Parameter Function Example Values
node_color Sets node colors 'red', 'lightblue', ['red', 'blue']
node_size Controls node size 300, 1000, [100, 500, 200]
with_labels Shows/hides node labels True, False
edge_color Sets edge colors 'gray', 'black', 'blue'

Conclusion

NetworkX combined with Matplotlib provides powerful tools for graph visualization. Use draw() for simple plots, customize with color and size parameters for better presentation, and leverage subplots for comparing different graph views or layouts.

Updated on: 2026-03-27T10:22:08+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements