给定一个邻接矩阵,如何用 matplotlib 绘制图形? [英] Given an adjacency matrix, How to draw a graph with matplotlib?

查看:45
本文介绍了给定一个邻接矩阵,如何用 matplotlib 绘制图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但可以优化.

推荐答案

如果您只想减少编写的代码量,您可能会对流行的 networkx 项目感兴趣.

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

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

Disclaimer: I am a contributor to networkx.

这篇关于给定一个邻接矩阵,如何用 matplotlib 绘制图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆