Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Resetting A Matplotlib From An Ipywidget Button

Tags:

When using iPyWidgets and Matplotlib in a Jupyter notebook, it is fairly easy to get a live-updating figure, even with multiple subplots, and multiple variables with multiple sliders. Simply set an interact to contain the activated plot function, and constructors for two slider variables:

%pylab inline
from ipywidgets import *
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

interact(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))

This could easily be extended to a plot where (say) three sliders control three polynomial coefficients all in a single window (i.e., no subplots).

But, it would be highly useful to have a reset button, which returns all variables to their default condition. How can I cause an ipywidget button's on_click method to affect the variables of the slider, and the figure itself?

like image 596
Novak Avatar asked Apr 08 '17 23:04

Novak


1 Answers

This can be done by leveraging the interactive function.

%pylab inline
from ipywidgets import widgets
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

def reset_values(b):
    """Reset the interactive plots to inital values."""
    my_plts.children[0].value = 1
    my_plts.children[1].value = 1

reset_button = widgets.Button(description = "Reset")
reset_button.on_click(reset_values)

my_plts = widgets.interactive(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))
display(my_plts, reset_button)

Can't stand hard-coded variables? Then replace the reset_values function with this more elastic version:

def reset_values(b):
    """Reset the interactive plots to inital values."""

    my_plts.children[0].value = my_plts.children[0].min
    my_plts.children[1].value = my_plts.children[1].min

Hope that helps.

like image 181
James Draper Avatar answered Oct 18 '22 15:10

James Draper