I have been attempting to optimize my matplotlib animation which involves adding a rectangle to the plot with each iteration. Since the animation function updates the entire set of patches with each iteration it is very slow for large sets of patches.
According to several sources, this process can be sped up by using a PatchCollection instead of looping over patches. This is my attempt:
from matplotlib import pyplot
from matplotlib import patches
from matplotlib import animation
from matplotlib.collections import PatchCollection
fig = pyplot.figure()
coords = [[1,0],[0,1],[0,0]] #arbitrary set of coordinates
ax = pyplot.axes(xlim=(0, len(coords)), ylim=(0, len(coords)))
ax.set_aspect('equal')
patchList = list()
for coord in coords:
patch = patches.Rectangle(coord, 1, 1, color="white")
ax.add_patch(patch)
patch.set_visible = True
patchList.append(patch)
rectangles = PatchCollection(patchList, animated=True)
ax.add_collection(rectangles)
black = []
white = ["white"]*len(patchList)
def animate(i):
black.append("black")
white.pop()
colors = black + white
print(colors)
rectangles.set_facecolors(colors)
print("%.2f%%..."%(100*float(i+1)/len(coords)))
return rectangles,
anim = animation.FuncAnimation(fig, animate,
# init_func=init,
frames=len(coords)-1,
interval=1,
blit=True,
repeat = False)
pyplot.show()
The animation never updates. It is frozen on an empty plot.
I would be open to other means of optimizing this. The current solution seems pretty verbose for just adding a single rectangle each frame.