Open In App

Visualizing the complement of a graph using networkx

Given a graph G complement of the graph is obtained by removing the edges contained in G from the complete graph having the same number of nodes as G.  

Example:



Initial Graph G:

G

The complement of G:



G Complement

Realizing Complement using Python :

We will use networkx.complement() function for our task

Syntax:

networkx.complement()

  • Returns the complement of the graph object passed.
  • The value returned is of the same type of the value passed i.e networkx graph object.
  • G is the initial object passed.
  • Although the complement is being created but no self-loops and parallel edges are created.

Working of complement(G) function:

An edge (n,n2) where n is iterator used to iterate over G is added to complement graph if following conditions are met:

Approach:




# importing networkx module
import networkx as nx
  
# creating sample graph object
G = nx.path_graph(3)
  
# complement of G and saving in G_C
G_C = nx.complement(G)
  
  
# calling draw() to visualize the original graph
nx.draw(G, node_color='Green', with_labels=True)
  
  
# calling draw() to visualize the complement graph
nx.draw(G_C, node_color='Green', with_labels=True)

Output:

Original Graph

Complement Graph

By using the complement() method all the edges in G were removed and all other possibilities were added to the complement of G and printed.  

Article Tags :