Search⌘ K
AI Features

Creating Graphs in Python

Explore how to create basic and weighted graphs in Python using the NetworkX library. Learn to add nodes and edges, assign weights, and manipulate graphs to model real-world systems effectively.

Create a basic graph

To create a basic graph in Python, we can use the popular library NetworkX. It provides various functionalities for creating, analyzing, and manipulating graphs.

Let's consider the basic graph as follows:

Graph with two nodes (A and B) and one edge connecting them (edge A-B)
Graph with two nodes (A and B) and one edge connecting them (edge A-B)

We can use the following code to create our graph:

Python 3.8
import networkx as nx
# Create an empty graph
G = nx.Graph()
# Add nodes to the graph
G.add_node("A")
G.add_node("B")
# Add edges between nodes
G.add_edge("A", "B")
  • Line 4: We create an empty graph using the nx.Graph() function.

  • Lines 7–8: We add two nodes A and B using the add_node() function.

  • Line 11: We add an edge between nodes A and B using the add_edge() function.

Note: To add multiple nodes and edges to a graph in NetworkX, we can use the ...