Creating Graphs in Python

Learn how to create, visualize, and manipulate weighted graphs in Python using the NetworkX library.

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:

Press + to interact
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:

Press + to interact
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 ...