programmatic control of Jupyter interactive

42 views
Skip to first unread message

Randy Heiland

unread,
Feb 23, 2020, 10:15:25 PM2/23/20
to Project Jupyter
Hello,

I'm doing the equivalent of this:
        self.i_plot = interactive(self.plot_file, frame=(0, num_files), continuous_update=False)  
   
    def plot_file(self, file_num):
       ...

and would like to have a "Play" button be able to programmatically step through all files. However, I can't directly call 'plot_file(fnum)' as it plots multiple (matplotlib) frames, rather than use the same frame. Any suggestions?

thanks, Randy

Randy Heiland

unread,
Feb 24, 2020, 8:52:16 PM2/24/20
to Project Jupyter
In case anyone's interested, here's a simple example:

%matplotlib inline
import matplotlib.pyplot as plt
import random
import numpy as np
from ipywidgets import interactive, ToggleButton, HBox

redraw_fig = True

def update_plot(p):
    global redraw_fig
    if (redraw_fig):
        plt.figure(1)
    nx = 20
    ny = 10
    x = np.linspace(1, nx, nx)
    y = np.linspace(1, ny, ny)
    xv, yv = np.meshgrid(x, y)

    rgb = np.zeros((nx*ny,3))
    rgb[:,0] += 1  # default to all red

    for rval in random.sample(range(nx*ny), int(p/100. * (nx*ny))):
        rgb[:][rval] = [0,1,0]

    area=200
    plt.scatter(xv, yv, marker='s', s=area, c=rgb)
    plt.axis('off')
    plt.xticks([])
    plt.yticks([])
#     plt.show()

def play_cb(b):
    global redraw_fig
    redraw_fig = False
    for idx in range(0,100,20):
        print('>>> ',idx)
        update_plot(idx)

                
plot = interactive(update_plot, p=(0, 100), continuous_update=False)
output = plot.children[-1]
output.layout.height = '300px'

play_btn = ToggleButton( description='Play' )
play_btn.observe(play_cb)

gui = HBox([plot,play_btn])
gui
Reply all
Reply to author
Forward
0 new messages