Member-only story

Network Graph using Python

Python Coding
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 as nx, which is a library for creating, analyzing, and visualizing networks (graphs).
  • matplotlib.pyplot is imported as plt for plotting and visualizing the graph.

Creating a Graph Object

  • G = nx.Graph()
  • nx.Graph() initializes an undirected graph object G 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))

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

Responses (1)