Plot NetworkX Graph from Adjacency Matrix in CSV file

前端 未结 3 2291
一生所求
一生所求 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:40

    I made a small csv called mycsv.csv that has the following:

    ,a,b,c,d
    a,0,1,0,1
    b,1,0,1,0
    c,0,1,0,1
    d,1,0,1,0
    

    You don't have a ',' as the first character on the first row, but instead you have a space, so if this is an error on my part let me know. The general idea will be the same. Read in the csv as such:

    from numpy import genfromtxt
    import numpy as np
    mydata = genfromtxt('mycsv.csv', delimiter=',')
    print(mydata)
    print(type(mydata))
    

    This prints:

    [[ nan  nan  nan  nan  nan]
     [ nan   0.   1.   0.   1.]
     [ nan   1.   0.   1.   0.]
     [ nan   0.   1.   0.   1.]
     [ nan   1.   0.   1.   0.]]
    
    

    Now that we have the csv read in as a numpy array we need to extract just the adjacency matrix:

    adjacency = mydata[1:,1:]
    print(adjacency)
    

    This prints:

    [[ 0.  1.  0.  1.]
     [ 1.  0.  1.  0.]
     [ 0.  1.  0.  1.]
     [ 1.  0.  1.  0.]]
    

    You can just slice your numpy array as needed if my small example isn't exactly as yours.

    To plot the graph you will need to import matplotlib and networkx:

    import matplotlib.pyplot as plt
    import networkx as nx
    
    def show_graph_with_labels(adjacency_matrix, mylabels):
        rows, cols = np.where(adjacency_matrix == 1)
        edges = zip(rows.tolist(), cols.tolist())
        gr = nx.Graph()
        gr.add_edges_from(edges)
        nx.draw(gr, node_size=500, labels=mylabels, with_labels=True)
        plt.show()
    
    show_graph_with_labels(adjacency, make_label_dict(get_labels('mycsv.csv')))
    

    Here's a short tutorial on graphs with python.

    graph from csv

提交回复
热议问题