Python:从Ipywidget按钮重置Matplotlib [英] Python: Resetting A Matplotlib From An Ipywidget Button
问题描述
在Jupyter笔记本中使用iPyWidgets和Matplotlib时,即使具有多个子图和具有多个滑块的多个变量,也很容易获得实时更新的图形.只需设置interact
即可包含已激活的绘图功能以及两个滑块变量的构造函数:
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).
但是,有一个重置按钮非常有用,该按钮会将所有变量恢复为默认状态.如何使ipywidget按钮的on_click方法影响滑块的变量以及图形本身?
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?
推荐答案
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)
不能忍受硬编码的变量吗?然后将reset_values
函数替换为更具弹性的版本:
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
希望有帮助.
这篇关于Python:从Ipywidget按钮重置Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!