Plot NetworkX Graph from Adjacency Matrix in CSV file

前端 未结 3 2282
一生所求
一生所求 2020-12-08 16:57

I have been battling with this problem for a little bit now, I know this is very simple - but I have little experience with Python or NetworkX. My question is very simple, I

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 17:31

    This can be done easily by using pandas and networkx.

    For example, I have created a small csv file called test.csv as

    A,B,C,D,E,F,G,H,I,J,K
    A,0,1,1,0,1,1,1,1,0,1,0
    B,1,0,0,0,1,1,1,1,0,1,0
    C,1,0,0,0,1,1,1,1,0,1,0
    D,0,0,0,0,1,0,1,1,0,1,0
    E,1,0,0,0,1,1,1,1,0,1,0
    F,0,0,1,0,1,0,0,0,0,1,0
    G,1,0,0,0,0,0,0,1,0,0,0
    H,1,0,0,0,1,1,1,0,0,1,0
    I,0,0,0,1,0,0,0,0,0,0,0
    J,1,0,0,0,1,1,1,1,0,1,0
    K,1,0,0,0,1,0,1,0,0,1,0
    

    You can read this csv file and create graph as follows

    import pandas as pd
    import networkx as nx
    input_data = pd.read_csv('test.csv', index_col=0)
    G = nx.DiGraph(input_data.values)
    

    For plotting this graph use

    nx.draw(G)
    

    You would be getting a plot something similar to this.

    Output of <code>nx.draw(G)</code>

提交回复
热议问题