Given an adjacency matrix, How to draw a graph with matplotlib?

Diego Silvera picture Diego Silvera · May 30, 2017 · Viewed 7.6k times · Source

I have an undirected graph described by its adjacency matrix (a numpy array) and I want to plot it, with vertices placed in a n-regular polygon. This code works:

n = adyacency_mathix.shape[0]
axis = np.linspace(0, 2*np.pi, n, endpoint=False)
x, y = np.cos(axis), np.sin(axis)
for i in xrange(n):
    for j in xrange(i + 1, n):
        if self.matrix[i, j] == 1:
            pyplot.plot((x[i], x[j]), (y[i], y[j]), color = 'blue')
pyplot.show()

but can be optimized.

Answer

Arya McCarthy picture Arya McCarthy · May 30, 2017

You may be interested in the popular networkx project, if you're interested in simply reducing the amount of code you write.

import matplotlib.pyplot as plt
import networkx as nx

# Generating sample data
G = nx.florentine_families_graph()
adjacency_matrix = nx.adjacency_matrix(G)

# The actual work
# You may prefer `nx.from_numpy_matrix`.
G2 = nx.from_scipy_sparse_matrix(adjacency_matrix)
nx.draw_circular(G2)
plt.axis('equal')

florentine circular graph

Disclaimer: I am a contributor to networkx.