title: Updating matplotlib figures within a for loop in python
body: <p>I am trying to move a magnetic object and update its magnetic field which is then plotted in a for loop. I want to update the matplotlib figures such that the last figure is deleted before the latest one is shown (with delay as can be seen). I want this to happen in one window (I might be using the wrong technical term) only. Currently it creates a new figure every time it updates the magnetic field. I tried using plt.cla(), plt.close(), and plt.clf() without success. The code is given below. Any help will be much appreciated</p>
  <pre><code>import matplotlib.pyplot as plt
  import numpy as np
  from magpylib.source.magnet import Box,Cylinder
  from magpylib import Collection, displaySystem
  
  # create magnets
  s1 = Box(mag=(0,0,600), dim=(3,3,3), pos=(-4,0,20))
  
  # calculate the grid
  xs = np.linspace(-15,10,33)
  zs = np.linspace(-5,25,44)
  POS = np.array([(x,0,z) for z in zs for x in xs])
  X,Z = np.meshgrid(xs,zs)
  
  for i in range(20):
      Bs = s1.getB(POS).reshape(44,33,3)     #B-field
      s1.move((0,0,-1))
  
      # create figure
      fig = plt.figure(figsize=(5,9))
  
      # display field in xz-plane using matplotlib
      U,V = Bs[:,:,0], Bs[:,:,2]
      plt.streamplot(X, Z, U, V, color=np.log(U**2+V**2))
  
      plt.show()
      
      sleep(0.2)```
  </code></pre>