使用 IPython 绘制双变量交互函数
Bi-variant interactive function plotting using IPython
我想绘制两个具有不同频率的函数,比如说正弦和余弦 --- 所以第一个变量是要绘制的函数,第二个是它的频率。我想要一个选择功能的选择器小部件和一个选择频率的滑块。是否可以使用 interact
实现此目的,还是我需要更复杂的设置?
是的,这应该可以通过 interact
要进一步阅读,github 存储库中有几个 example notebooks
可以用作交互式小部件的介绍。
%matplotlib inline
from IPython.html import widgets
import numpy as np
import matplotlib.pyplot as plt
fun_map = {
"sin": np.sin,
"cos": np.cos
}
func_name = widgets.Dropdown(
options=['sin', 'cos'],
value='sin',
description='Function:',
)
freq = widgets.FloatSlider(
min=1,
max=5,
value=1,
description='Parameter:'
)
def plot_fun(func_name, freq, fun_map):
f = fun_map[func_name]
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, f(freq * x))
res = widgets.interact(plot_fun, freq=freq, func_name=func_name,
fun_map=widgets.fixed(fun_map))
这是结果:
我想绘制两个具有不同频率的函数,比如说正弦和余弦 --- 所以第一个变量是要绘制的函数,第二个是它的频率。我想要一个选择功能的选择器小部件和一个选择频率的滑块。是否可以使用 interact
实现此目的,还是我需要更复杂的设置?
是的,这应该可以通过 interact
要进一步阅读,github 存储库中有几个 example notebooks
可以用作交互式小部件的介绍。
%matplotlib inline
from IPython.html import widgets
import numpy as np
import matplotlib.pyplot as plt
fun_map = {
"sin": np.sin,
"cos": np.cos
}
func_name = widgets.Dropdown(
options=['sin', 'cos'],
value='sin',
description='Function:',
)
freq = widgets.FloatSlider(
min=1,
max=5,
value=1,
description='Parameter:'
)
def plot_fun(func_name, freq, fun_map):
f = fun_map[func_name]
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, f(freq * x))
res = widgets.interact(plot_fun, freq=freq, func_name=func_name,
fun_map=widgets.fixed(fun_map))
这是结果: