2

I want to make a figure and interactively change it with ipywidgets. When I use %matplotlib notebook, the widget call needs to be in a separate code cell, which is odd. Here is the code that doesn't work

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
%matplotlib notebook

fig = plt.figure(figsize=(6, 6))
ax1 = plt.subplot(111, aspect='equal')
ax1.set_xlim(-5,5)
ax1.set_ylim(-5,5)
circ = Circle((0,0), radius=1)
ax1.add_patch(circ)

def change_radius(r=1):
    circ.set_radius(r)

from ipywidgets import interact
interact(change_radius, r=(1.0, 5))

This only works when the last two lines are in a separate code cell, but then the widget is separated from the graph by the code cell. Does anybody know how to get it to work in one code cell with %matplotlib notebook ?

2
  • I think this is a limitation of the current implementation (which does not directly use ipywidgets but injects a good bit of custom js) which does not play as well with the display machinery as it should. Commented Mar 18, 2016 at 2:10
  • That's what I was worried about. Is this something that can be changed, or does that require a complete overhaul of the current implementation? Commented Mar 18, 2016 at 8:46

1 Answer 1

2

You should call the figure explicitly using display(fig) in change_radius():

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from IPython.display import display
%matplotlib notebook

fig = plt.figure(figsize=(6, 6))
ax1 = plt.subplot(111, aspect='equal')
ax1.set_xlim(-5,5)
ax1.set_ylim(-5,5)
circ = Circle((0,0), radius=1)
ax1.add_patch(circ)

def change_radius(r=1):
    circ.set_radius(r)
    display(fig)

from ipywidgets import interact
interact(change_radius, r=(1.0, 5))
Sign up to request clarification or add additional context in comments.

1 Comment

@MarkBakker No problem! make sure you also check out the ipywidget examples at their github repo. They are a useful source of info.

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.