如何使用Matplotlib加快绘制大量矩形的速度? [英] How to speed up the plot of a large number of rectangles with Matplotlib?

查看:87
本文介绍了如何使用Matplotlib加快绘制大量矩形的速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Matplotlib绘制大量矩形对象.这是一个带有n个随机生成的矩形的简单代码.

I need to plot a large number of rectangular objects with Matplotlib. Here a simple code with n randomly generated rectangles.

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,则将花费太多时间.是否有任何改进建议,或者在合理的时间内采用其他方法进行绘制?

With n=10000 it takes seconds, but if we increase the number of rectangles to 100K it takes too much time. Any suggestion to improve it, or different approach to have a plot in a reasonable time?

推荐答案

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

这篇关于如何使用Matplotlib加快绘制大量矩形的速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆