Sunday, November 17, 2024
Google search engine
HomeLanguagesVisualizing the complement of a graph using networkx

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:

  • n and n2 are not neighbours i.e n2 are in the adjacency list of n and vice versa.
  • And n != n2.
  • n and n2 both are part of G.

Approach:

  • We will import networkx with an alias nx.
  • Create a sample graph object G using path_graph() function.
  • We will then call complement function passing G as an argument.
  • We will capture the object returned by complement function in another object G_C.
  • We will then call draw() function passing G_C as an argument which will display of the complement graph.

Python3




# 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.  

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000neveropen! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments