Reputation: 831
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
?
Upvotes: 2
Views: 601
Reputation: 1345
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))
Upvotes: 2