NetworkX and Matplotlib Graph Tutorial | Generated by AI

Home 2025.10

Installing the Libraries

To use NetworkX and Matplotlib for drawing diagrams, install them if needed:

Install via pip:

pip install networkx matplotlib

For faster rendering, Matplotlib recommends installing NumPy (pip install numpy).

Basic Setup and Example

  1. Import libraries:
    import networkx as nx
    import matplotlib.pyplot as plt
    
  2. Create a graph:
    Use NetworkX to build a simple undirected graph (you can customize with directed graphs, weighted edges, etc.):
    G = nx.Graph()  # Create an empty graph
    G.add_nodes_from([1, 2, 3, 4, 5])  # Add nodes (e.g., 5 nodes)
    G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)])  # Add edges (connections)
    
  3. Draw and display the diagram:
    Use Matplotlib’s backend for visualization:
    nx.draw(G, with_labels=True)  # Draw the graph with node labels
    plt.show()  # Display the plot
    

This produces a basic circular layout of the graph (a cycle with 5 nodes).

Advanced Customizations

Tips and Resources


Back

x-ai/grok-code-fast-1

Donate