2

The toy example provided in the ipywidgets docs is the following:

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

def f(m, b):
    plt.figure(2)
    x = np.linspace(-10, 10, num=1000)
    plt.plot(x, m * x + b)
    plt.ylim(-5, 5)
    plt.show()

interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot

I attempted the following, which does not work:

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_ylim(-5, 5)

def f(m, b):
    global ax
    ax.cla()
    x = np.linspace(-10, 10, num=100)
    ax.plot(x, m * x + b)
    # fig.canvas.draw() ?
    

interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot

What goes wrong when using Axes objects in this context?

bzm3r
  • 3,113
  • 6
  • 34
  • 67

2 Answers2

1

Two solutions:

Either you move the figure creation inside function i.e.

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

def f(m, b):
    # move here
    fig, ax = plt.subplots()
    ax.set_ylim(-5, 5)
    ...
    
...

enter image description here

Or use matplotlib's notebook mode instead of inline mode: %matplotlib notebook.

kHarshit
  • 11,362
  • 10
  • 52
  • 71
0

You have to specify the figure number in the subplots function if you want matplotlib inline to update the plots instead of creating new ones.

plt.subplots(nrows=2, ncols=2, figsize=(figx, figy), num=1)