pythongraphlinenetworkxcomplement

NetworkX: Line graph and complement of it


I have to generate and draw a line graph and complement of for a second graph that i load from .txt file as a adjacency list. I've already tried many ways, but i'm getting only errors. So far no progress...

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

a = np.loadtxt('adjacencymatrix.txt', dtype=int) 

Solution

  • You can try taking complement of the adjacency matrix. Here I am assuming your adjacency matrix consists of 0's and 1's. So assume the following is you adjacency matrix, stored inside adjacency.txt :

    0,0,1,0,1,1
    0,0,1,1,0,1
    1,1,0,0,1,0
    0,1,0,0,1,0
    1,0,1,1,0,1
    1,1,0,0,1,0
    

    Now lets plot this graph

    import matplotlib.pyplot as plt
    import networkx as nx
    import numpy as np
    A = np.loadtxt('adjacency.txt', delimiter=',', dtype=int) 
    G = nx.from_numpy_matrix(np.array(A))
    nx.draw(G, with_labels=True)
    

    enter image description here

    Now to dray the complement the graph, I am assuming here that you mean to somehow complement the edges. So, since you have the adjacency matrix, you can invert it using np.bitwise_xor (or any other way to change 1s to 0s and vice-versa), since XOR-ing a bit with 1 inverts it (i.e. 1 becomes 0 and 0 becomes 1)

    B = np.bitwise_xor(A,1)
    G = nx.from_numpy_matrix(np.array(B))
    nx.draw(G, with_labels=True)
    

    enter image description here

    As you can se the graph edges are inverted. For example in the initial graph node 3 had edges to node 1 and node 4, while in the inverted graph it has edges to other nodes, i.e. nodes 2, 5 and 3

    ** Note:** There are other ways to invert a numpy array. There is no hard and fast rule to use bitwise_xor. Here is a more easier way to do it.