Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
Marco Pavan Avatar asked Nov 24 '15 22:11

Marco Pavan


Video Answer


1 Answers

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()
like image 153
Marius Avatar answered Nov 15 '22 09:11

Marius