Friday, December 27, 2024
Google search engine
HomeLanguagesCreating a Path Graph Using Networkx in Python

Creating a Path Graph Using Networkx in Python

A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function.

Properties of Path Graph:

  • The number of nodes in a path graph(Pn) is N.
  • The number of edges in a path graph(Pn) is N-1.
  • The diameter of the path graph(Pn) i.e maximum distance between any pair of vertices is N-1 which is between 1st and last node.
  • The chromatic number of Path Graph is 2.
  • Nodes are assigned labels from 0 to N-1
  • Terminal vertices have degree 1 and every other vertex has degree 2.
  • A path graph is a connected graph.
  • Path graph contains no cycle in it.
  • Although the path graph is connected but the removal of any edge will make it unconnected as no cycle is there in Path Graph.
  • It is a Planar Graph.

Functions used

We will use the networkx module for realizing a Path graph. It comes with an inbuilt function networkx.path_graph() and can be illustrated using the networkx.draw() method. This method is straightforward method of creating a desired path graph using appropriate parameters. 

Syntax:  path_graph(n, create_using=None)

Parameter:

  • n: Number of nodes we want in path graph.
  • create_using: We can simply pass None or pass nx.DiGraph() as a value to this argument sending nx.Digraph() will lead to creation of a directed path graph.

Approach:

  • Import module
  • Create path graph object using path_graph() function as mentioned above.
  • Pass appropriate parameters to the functions
  • Display plot

Program:

Python3




# import required module
import networkx as nx
 
# create object
G = nx.path_graph(5, create_using=nx.DiGraph())
 
# illustrate graph
nx.draw(G, node_color='green')


Output:

RELATED ARTICLES

Most Popular

Recent Comments