【问题标题】:How to speed up the plot of a large number of rectangles with Matplotlib?如何使用 Matplotlib 加快绘制大量矩形的速度?
【发布时间】:2015-11-24 22:43:47
【问题描述】:

我需要用 Matplotlib 绘制大量矩形对象。 这是一个包含 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()

n=10000 需要几秒钟,但如果我们将矩形的数量增加到 100K,则需要太多时间。 有什么改进它的建议,或者在合理的时间内有一个情节的不同方法?

【问题讨论】:

标签: python matplotlib plot


【解决方案1】:

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

【讨论】:

  • 非常感谢。我确认您的方法可以将速度提高 3 倍。使用 10 万个对象需要 40 秒而不是 2 分 30 秒。
猜你喜欢
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多