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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With