Visualize Graphs in Python
Prerequisites: Graph Data Structure And Algorithms
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.
In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx library.
Installation:
To install this module type the below command in the terminal.
pip install networkx
Below is the implementation.
import networkx as nx
import matplotlib.pyplot as plt
class GraphVisualization:
def __init__( self ):
self .visual = []
def addEdge( self , a, b):
temp = [a, b]
self .visual.append(temp)
def visualize( self ):
G = nx.Graph()
G.add_edges_from( self .visual)
nx.draw_networkx(G)
plt.show()
G = GraphVisualization()
G.addEdge( 0 , 2 )
G.addEdge( 1 , 2 )
G.addEdge( 1 , 3 )
G.addEdge( 5 , 3 )
G.addEdge( 3 , 4 )
G.addEdge( 1 , 0 )
G.visualize()
|
Output:
Last Updated :
17 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...