在matplotlib中绘制大量点和边

4 投票
2 回答
8151 浏览
提问于 2025-04-17 05:58

我有一些点(大约3000个)和边(大约6000条),它们的格式是这样的:

points = numpy.array([1,2],[4,5],[2,7],[3,9],[9,2])
edges = numpy.array([0,1],[3,4],[3,2],[2,4])

这里的边是指向点的索引,也就是说,每条边的起始和结束坐标是由以下内容给出的:

points[edges]

我在寻找一种更快或更好的方法来绘制这些边。目前我使用的是:

from matplotlib import pyplot as plt
x = points[:,0].flatten()
y = points[:,1].flatten()
plt.plot(x[edges.T], y[edges.T], 'y-') # Edges
plt.plot(x, y, 'ro') # Points
plt.savefig('figure.png')

我听说过lineCollections,但不太确定怎么用。有没有更直接使用我数据的方法?这里的瓶颈是什么呢?

一些更真实的测试数据,绘制的时间大约是132秒:

points = numpy.random.randint(0, 100, (3000, 2))
edges = numpy.random.randint(0, 3000, (6000, 2))

2 个回答

3

你也可以只用一个绘图命令来完成,这样比用两个命令要快很多(虽然实际上和添加一个线集合的效果差不多)。

import numpy
import matplotlib.pyplot as plt

points = numpy.array([[1,2],[4,5],[2,7],[3,9],[9,2]])
edges = numpy.array([[0,1],[3,4],[3,2],[2,4]])

x = points[:,0].flatten()
y = points[:,1].flatten()

plt.plot(x[edges.T], y[edges.T], linestyle='-', color='y',
        markerfacecolor='red', marker='o') 

plt.show()
5

我发现下面这个方法要快得多:

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
lc = LineCollection(points[edges])
fig = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(points[:,0].min(), points[:,0].max())
plt.ylim(points[:,1].min(), points[:,1].max())
plt.plot(points[:,0], points[:,1], 'ro')
fig.savefig('full_figure.png')

还有没有更快的方法呢?

撰写回答