title: Animate a collection of patches in matplotlib
body: <p>I'm trying to animate a set of particles that follow trajectories in x, y and z. Each object has a specific radius which is relevant in axis units, which is why I want each object to be represented by a Circle patch, where I can specify the size of the patch (as opposed to a scatter plot, where I have to convert the size to axis units). </p>
  
  <p>The other constraint is that I want the patches to be colored according to a colormap, with the color of the patch determined by the value of z. </p>
  
  <p>The only way I have found of plotting a set of patches with a colormap is by putting them inside a collection. So, this successfully produces one frame </p>
  
  <pre><code>import numpy as np
  import matplotlib.pyplot as plt
  import matplotlib.animation as anm
  import matplotlib.collections as clt
  
  fig, ax = plt.subplots(1,1,figsize=(7,7))
  
  ax.set_xlim(-1,1)
  ax.set_ylim(-1,1)
  
  n_of_particles = 3
  frames = 10
  
  radius = 0.05
  x = 0.5*np.random.randn(frames,n_of_particles)
  y = 0.5*np.random.randn(frames,n_of_particles)
  z = 0.5*np.random.randn(frames,n_of_particles)
  
  patches = []
  for p in range(n_of_particles):
      circle = plt.Circle((x[0,p], y[0,p]), radius)
      patches.append(circle)
  
  collection = clt.PatchCollection(patches, cmap=plt.cm.jet, alpha=0.4)
  collection.set_array(z[0,:])
  collection.set_clim([-1, 1])
  plt.colorbar(collection)
  
  ax.add_collection(collection)
  </code></pre>
  
  <p>But how do I animate it?</p>
  
  <p>I have tried to add at the end (instead of <code>ax.add_collection(collection)</code>)</p>
  
  <pre><code>def animate(frame):
      patches = []
      for p in range(n_of_particles):
          circle = plt.Circle((x[frame,p], y[frame,p]), radius)
          patches.append(circle)
  
      collection = clt.PatchCollection(patches, cmap=plt.cm.jet, alpha=0.4)
      collection.set_array(z[0,:])
  
      ax.add_collection(collection)
      return collection,
  </code></pre>
  
  <p>and then:</p>
  
  <pre><code>anim = anm.FuncAnimation(fig, animate,
                                 frames=10, interval=100, blit=True)
  HTML(anim.to_html5_video())
  </code></pre>
  
  <p>But it doesn't erase the previous frame. </p>
  
  <p>Ideally, I would prefer to change the position of the patches, instead of redefining them. But I don't know how to modify a collection. </p>
  
  <p>Any ideas?</p>