在matplotlib中绘制大量点和边

4

我有大约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))

1
也许这篇文章http://jbdeaton.com/2011/speed-up-plot-rendering-in-pythonmatplotlib/能够帮到你。在plot()函数调用中添加rasterized=True参数。 - David Poole
2个回答

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

还有什么更快的方法吗?


3

您也可以通过一次绘制来完成,这比两次绘制要快得多(虽然与添加LineCollection可能基本相同)。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接