[英]How to speed up the plot of a large number of rectangles with Matplotlib?
I need to plot a large number of rectangular objects with Matplotlib. 我需要使用Matplotlib绘制大量矩形对象。 Here a simple code with n randomly generated rectangles.
这是一个简单的代码,有n个随机生成的矩形。
import matplotlib
import matplotlib.pyplot as plt
import random
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
plt.xlim([0, 1001])
plt.ylim([0, 1001])
n=10000
for i in range(0,n):
x = random.uniform(1, 1000)
y = random.uniform(1, 1000)
ax.add_patch(matplotlib.patches.Rectangle((x, y),1,1,))
plt.show()
With n=10000 it takes seconds, but if we increase the number of rectangles to 100K it takes too much time. n = 10000时需要几秒钟,但如果我们将矩形数增加到100K则需要花费太多时间。 Any suggestion to improve it, or different approach to have a plot in a reasonable time?
是否有任何建议可以改善它,或采用不同的方法在合理的时间内制作情节?
Adding all the patches to the plot at once with a PatchCollection
produces around a 2-3x speedup with n = 10,000, I'm not sure how well it will scale to larger numbers though: 使用
PatchCollection
一次性将所有补丁添加到绘图中产生大约2-3倍的加速,n = 10,000,我不确定它将扩展到更大的数字,但是:
from matplotlib.collections import PatchCollection
import matplotlib
import matplotlib.pyplot as plt
import random
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
plt.xlim([0, 1001])
plt.ylim([0, 1001])
n=10000
patches = []
for i in range(0,n):
x = random.uniform(1, 1000)
y = random.uniform(1, 1000)
patches.append(matplotlib.patches.Rectangle((x, y),1,1,))
ax.add_collection(PatchCollection(patches))
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.