给定邻接矩阵,如何用matplotlib绘制图形?

时间:2017-05-30 20:38:36

标签: python numpy matplotlib plot graph-drawing

我有一个由其邻接矩阵(一个numpy数组)描述的无向图,我想绘制它,顶点放在一个n正多边形中。此代码有效:

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()

但可以进行优化。

1 个答案:

答案 0 :(得分:9)

如果您只想减少自己编写的代码数量,那么您可能会对热门的networkx项目感兴趣。

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

免责声明:我是networkx的撰稿人。