Member-only story
Network Graph using Python
2 min readNov 10, 2024
This code snippet demonstrates how to create and visualize a simple network graph using the networkx
and matplotlib
libraries in Python.
Explanation
Importing Libraries
import networkx as nx import matplotlib.pyplot as plt
network
is imported asnx
, which is a library for creating, analyzing, and visualizing networks (graphs).matplotlib.pyplot
is imported asplt
for plotting and visualizing the graph.
Creating a Graph Object
G = nx.Graph()
nx.Graph()
initializes an undirected graph objectG
that will hold nodes and edges.
Adding Nodes
G.add_nodes_from(["A", "B", "C", "D", "E"])
G.add_nodes_from(...)
adds multiple nodes to the graph. Here, nodes labeled "A", "B", "C", "D", and "E" are added.
Adding Edges
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"), ("C", "E")] G.add_edges_from(edges)
edges
is a list of tuples, where each tuple represents an edge (connection) between two nodes.G.add_edges_from(edges)
adds these edges to the graph.
Plotting the Graph
plt.figure(figsize=(8, 6))