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

Die*_*era 2 python plot numpy matplotlib 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()
Run Code Online (Sandbox Code Playgroud)

但可以优化.

Ary*_*thy 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')
Run Code Online (Sandbox Code Playgroud)

佛罗伦萨圆形图

免责声明:我是贡献者networkx.

  • 肯定有.[`draw_circular`]的文档(https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_circular.html#networkx.drawing.nx_pylab.draw_circular)指出你可以使用[`draw_networkx`]中的关键字args(https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html#networkx.drawing.nx_pylab.draw_networkx ),其中一个是`with_labels = True`. (2认同)