Search code examples
pythonmatrixgraphnetworkxadjacency-matrix

convert a simple matrix to incidence matrix with python


i want to make graph network from incidence Matrix, but i don't have an incidence Matrix, i have just a simple Matrix.so my question is: how to convert a simple Matrix to a incidence Matrix to draw a graph network with python?

enter image description here


Solution

  • Both matrices are adjacency matrices. The most important thing is to know that they are different datatypes:

    import pandas as pd
    import numpy as np
    
    adjacency = [[0,0,-1,0,0], [1,1,-1,-1,0], [1,-1,0,0,0], [1,0,0,-1,0], [1,0,1,-1,1]]
    df = pd.DataFrame(adjacency, columns = ['A','B','C','D','E'], index = ['A','B','C','D','E'])
    

    This results in different methods of handling incidencies as well as different structure of graph:

    enter image description here

    As you can note easily, first method uses automatic assignment of node labels to indices 0, 1, 2, 3, 4.

    Another surprising facts: you don't need to collect weights manually. They are stored in weight attribute of edges.

    Usage:

    You can access edge attributes with nx.get_edge_attributes(G, 'weight'). This is my simplified version of diagram structure:

    G = nx.from_pandas_adjacency(df)
    pos = nx.circular_layout(G)
    nx.draw(G, pos, with_labels=True, bbox = dict(fc="lightgreen", ec="black", boxstyle="circle", lw=3),
        width=2, arrowsize=30)
    nx.draw_networkx_edge_labels(G, pos, edge_labels = nx.get_edge_attributes(G, 'weight'))
    plt.show()