且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Matplotlib加快绘制大量矩形的速度?

更新时间:2023-01-31 09:00:46

使用 PatchCollection 一次性将所有补丁添加到图中,会产生2-3倍的加速,n = 10,000,我我不确定它会如何扩展到更大的数字:

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:

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