pythongraphnumpy

Converting adjacency matrix given as ndarray into graph


I'm working on this Python program, which computes displacement of nodes in a given undirected graph via some algorithm. My output consists of an adjacency matrix in form of a numpy ndarray and another numpy ndarray holding the coordinates (2D) of each node.

I've been looking into ways of plotting the resulting Graph and stumbled across igraph and NetworkX. I did not use them yet, but I know they can convert an adjacency matrix into a graph, in this case I would not be using my coordinates though. So I wonder, how can I use both for graphical representation of my graph?

I could imagine I would have to use both arrays to create a different kind of object, which itself can be converted by NetworkX/igraph.


Solution

  • networkx solution:

    The draw nx.function: takes in a optional second argument of the positions:

    import numpy as np
    import networkx as nx
    import pylab as plt
    
    A = np.array([[0,0,1,0],[1,0,0,0],[1,0,0,1],[1,0,0,0]])
    G = nx.DiGraph(A)
    
    pos = [[0,0], [0,1], [1,0], [1,1]]
    nx.draw(G,pos)
    plt.show()
    

    enter image description here