Plot NetworkX Graph from Adjacency Matrix in CSV file

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.]]
<type 'numpy.ndarray'>

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


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>


This is identical to Scott's excellent answer but handles correctly nodes without edges.

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()
    all_rows = range(0, adjacency_matrix.shape[0])
    for n in all_rows:
        gr.add_node(n)
    gr.add_edges_from(edges)
    nx.draw(gr, node_size=900, labels=mylabels, with_labels=True)
    plt.show()