title: Interactive matplotlib using ipywidgets
body: <p>I want to implement an <em>interactive plot</em> using <strong>Matplotlib</strong> and <strong>ipywidgets</strong> in IPython (python3). So, how I can do this efficiently (change smoothly without delay)?</p>
  
  <p>And another question is why this code works?!</p>
  
  <pre><code>from ipywidgets import *
  import numpy as np
  import matplotlib.pyplot as plt
  %matplotlib inline
  
  x = np.linspace(0, 2 * np.pi)
  
  def update(w = 1.0):
      fig = plt.figure()
      ax = fig.add_subplot(1, 1, 1)
      ax.plot(x, np.sin(w * x))
  
      fig.canvas.draw()
  
  interact(update);
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/4ROoi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4ROoi.png" alt="enter image description here"></a></p>
  
  <p>But, this doesn't work?!</p>
  
  <pre><code>from ipywidgets import *
  import numpy as np
  import matplotlib.pyplot as plt
  %matplotlib inline
  
  x = np.linspace(0, 2 * np.pi)
  fig = plt.figure()
  ax = fig.add_subplot(1, 1, 1)
  line, = ax.plot(x, np.sin(x))
  
  def update(w = 1.0):
      line.set_ydata(np.sin(w * x))
      fig.canvas.draw()
  
  interact(update);
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/fWQch.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fWQch.png" alt="enter image description here"></a></p>