askvity

How to Plot a Graph using NetworkX

Published in Graph Visualization Python 4 mins read

To plot a graph data structure in Python, you typically use dedicated libraries like networkx combined with plotting libraries such as matplotlib.

Before you can plot a graph, you need to represent its structure in Python. As mentioned in the reference, graphs can be implemented using adjacency lists or adjacency matrices. An adjacency list uses a dictionary of lists where keys represent vertices and values are lists of adjacent vertices. An adjacency matrix uses a 2D array where the value at matrix[i][j] indicates the presence (or weight) of an edge between vertex i and vertex j.

While you can build a graph from these representations, the simplest way to plot in Python is often to use the high-level functionalities of the networkx library. You add nodes and edges directly to a networkx graph object, which can internally manage the structure, and then use its drawing functions (often powered by matplotlib) to visualize it.

The networkx library is the standard tool for graph creation, manipulation, and visualization in Python. Here's a typical workflow:

  1. Install Libraries: Ensure you have networkx and matplotlib installed:
    pip install networkx matplotlib
  2. Create a Graph Object: Instantiate a graph object (e.g., Graph for undirected, DiGraph for directed).
  3. Add Nodes and Edges: Populate the graph with nodes and edges. You can do this manually or potentially by iterating through an existing adjacency list or matrix representation you might have.
  4. Draw the Graph: Use networkx's drawing functions, which utilize matplotlib to render the graph.

Here's a simple example:

import networkx as nx
import matplotlib.pyplot as plt

# 1. Create a graph object (undirected graph)
G = nx.Graph()

# 2. Add nodes and edges
# You could add nodes/edges based on an adjacency list or matrix
# For example, if you had an adjacency list like:
# adj_list = {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A'], 'D': ['B']}
# You would iterate through it to add edges to G.
# Or, add edges directly:
G.add_edge('A', 'B')
G.add_edge('A', 'C')
G.add_edge('B', 'D')
G.add_edge('C', 'E')
G.add_edge('D', 'E')

# 3. Define a layout (optional, but recommended)
# Layout algorithms determine the position of nodes
pos = nx.spring_layout(G) # Spring layout is common

# 4. Draw the graph
nx.draw(G, pos, with_labels=True, node_size=700, node_color='skyblue', font_size=10, font_weight='bold', edge_color='gray')

# Add title
plt.title("Example Data Structure Graph Plot")

# Display the plot
plt.show()

Key Aspects of Plotting

  • Representation: Although networkx provides a high-level interface, it works on underlying graph representations. If you have your graph defined as an adjacency list or matrix, you would first create your networkx graph by adding nodes and edges based on that structure.
  • Layout: Choosing an appropriate layout (spring_layout, circular_layout, spectral_layout, etc.) is crucial for making the graph readable.
  • Customization: matplotlib allows extensive customization of node colors, sizes, edge styles, labels, and more, making the plot visually informative.

In summary, you plot a graph data structure in Python by leveraging libraries like networkx to build the graph object (potentially based on an adjacency list or matrix implementation) and then using its drawing capabilities, often integrated with matplotlib, to visualize it.

Related Articles