I will show you how to make a diagram that can be clicked with IPython. The easiest way is to use the ʻinteract function (ʻIPython.html.widgets.interact
) that automatically creates an interactive UI.
Note 1) A little more detailed explanation than this article is summarized in nbviewer as How to use Interact, so if you are interested, there Please also.
Note 2) IPython Notebook for this article can be downloaded from nbviewer as it is. If you want to try interactive drawing easily, please.
Load the required modules first.
from __future__ import print_function
from IPython.html.widgets import interact, interactive, fixed
from IPython.html import widgets
Then, first define the function you want to operate interactively.
def f(x):
print(x)
Next, pass the function you want to operate as the first argument of the ʻinteract` function, and pass a similar argument (widget abbreviation) as a keyword argument. That's it. When you execute the code below, a slider will appear, which is fun to click.
interact(f, x=(-10, 10, 2));
So, the top and bottom are completely synonymous. The top is how to pass a widget abbreviation, and the bottom is how to pass an instance of widget.
interact(f, x=widgets.IntSliderWidget(min=-10, max=10, step=2, value=0));
If you want to set the initial value, use ʻinteract` as a decorator.
@interact(x=(-10, 10, 2))
def g(x=8):
print(x)
Typical widgets are as follows. The keyword argument of the ʻinteract` function is either the widget abbreviation on the left or the widget instance on the right.
Keyword arguments | Widget |
---|---|
True or False |
CheckboxWidget |
u'Hello World!' |
TextareaWidget |
Using integersvalue or (min,max) or (min,max,step) |
IntSliderWidget |
Using real numbersvalue or (min,max) or (min,max,step) |
FloatSliderWidget |
('orange','apple') or {'one':1,'two':2} |
DropdownWidget |
When combined with drawing, it will be even more fun to click. The figure below is a demo that dynamically draws $ y = A , sin (\ omega x + \ alpha) $. If you change the three parameters $ A \ in [0.1, 4.0], \ omega \ in [0.1, 4.0], \ alpha \ in [-\ pi, \ pi] $ with the slider, the figure will change accordingly. To do. This is fun!
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
@interact(amp=(0.1, 4.0, 0.1), omega=(0.1, 4.0, 0.1), phase=(-np.pi, np.pi, 0.1),
fn = {'sin': np.sin, 'cos': np.cos, 'tan': np.tan})
def h(amp=1.0, omega=1.0, phase=0.0, fn=np.sin):
domain=[-np.pi, np.pi]
x = np.linspace(domain[0], domain[1], 100)
y = amp * fn(omega * x + phase)
plt.plot(x, y)
plt.plot(-phase/omega, 0, 'or')
plt.xlim(domain)
plt.ylim([-4, 4])
Recommended Posts