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))
  • plt.figure(figsize=(8, 6)) sets the size of the plot to 8x6 inches.
  • nx.draw(G, with_labels=True, node_color="yellow", node_size=1000, edge_color="red", font_size=16, font_weight="bold")
  • nx.draw(...) visualizes the graph with various style options:
  • with_labels=True displays node labels.
  • node_color="yellow" makes the nodes yellow.
  • node_size=1000 sets the size of each node.
  • edge_color="red" makes the edges red.
  • font_size=16 and font_weight="bold" adjust the font size and weight for labels.
  • plt.title("Network Graph using Python") plt.show()
  • plt.title("Network Graph using Python") adds a title to the plot.
  • plt.show() displays the graph.

This will produce a network graph with labeled, yellow nodes connected by red edges.

--

--

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)

Write a response