3

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.