I would like to use the ipython notebook widgets to add some degree of interactivity to inline matplotlib plots.
In general the plot can be quite heavy and I want to on
The solution turns out to be really simple. To avoid showing the first figure we just need to add a close()
call before the interact
call.
Recalling the example of the question, a cell like this will correctly show a single interactive figure (instead of two):
fig, ax = plt.subplots()
ax.plot([3,1,2,4,0,5,3,2,0,2,4])
plt.close(fig)
vline = ax.axvline(1)
hline = ax.axhline(0.5)
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
display(fig)
interact(set_cursor, x=(1, 9, 0.01), y=(0, 5, 0.01))
A cleaner approach is defining the function add_cursor
(in a separate cell or script):
def add_cursor(fig, ax):
plt.close(fig)
vline = ax.axvline(1, color='k')
hline = ax.axhline(0.5, color='k')
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
display(fig)
interact(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
and then call it whenever we want to add an interactive cursor:
fig, ax = plt.subplots()
ax.plot([3,1,2,4,0,5,3,2,0,2,4])
add_cursor(fig, ax)