python - 按钮小部件添加新图而不是替换旧图
问题描述
我有一个使用小部件的功能,它工作得很好,但是滑块有点难以小步移动。
我想添加按钮以在单击时前进或后退一步。这在下面的代码中实现。myplot
我的问题是,当我从内部回调原始函数时on_button_
,它会再次绘制所有内容,但我只想要更新的散点图。
如您所见plt.close('all')
, 我已经尝试过。plt.show()
我的问题——我认为——是我找不到合适的地方来放置它们。
import ipywidgets as widgets
from ipywidgets import interact, interact_manual, Button, HBox, fixed
@interact
step = 0.1
def myplot(
x=(0.3, 3, step),
y=(0,8,1)):
###############
def on_button_next(b):
plt.close('all')
myplot(x+step, y=y)
def on_button_prev(b):
plt.close('all')
myplot(x-step, y=y)
button_next = Button(description='x+')
button_prev = Button(description='x-')
############################
if x>0.3 :
plt.figure(figsize=(9,7))
ax1 = plt.subplot()
ax1.scatter(x, y, marker='*', s=300)
ax1.set_xlim(0,2)
ax1.set_ylim(0,8)
##### buttons.
display(HBox([button_prev, button_next]))
button_next.on_click(on_button_next)
button_prev.on_click(on_button_prev)
################
return plt.show()
解决方案
通过删除plt.show()
andplt.close()
和写来解决display(fig)
andclear_output()
from IPython.display import clear_output
step=0.1
@interact
def myplot(
x=(0.3, 3, step),
y=(0,5,1)):
# ##############
def on_button_next(b):
clear_output()
myplot(x+step, y=y)
def on_button_prev(b):
clear_output()
myplot(x-step, y=y)
button_next = Button(description='x+')
button_prev = Button(description='x-')
##############
if x>0.3 :
#buttons
display(HBox([button_prev, button_next]))
button_next.on_click(on_button_next)
button_prev.on_click(on_button_prev)
##
fig = plt.figure()
plt.scatter(x, y, marker='*', s=300)
plt.xlim(0.3,2)
plt.ylim(0,8)
plt.close()
display(fig)
推荐阅读
- php - 在 DateTime (PHP) 中添加“x”小时、“x”分钟和“x”秒
- cucumber - 在 BDD 流中,何时/何地编写功能文件,何时/谁将其添加到代码库中?
- java - 在活动中初始化一个类并在其所有片段和相关弹出窗口中使用
- java - Hazelcast ItemListener 停止获取项目
- javascript - 无论如何,是否只有在不捆绑它们的情况下,使用 webpack 缩小 node_modules 的组件并做出反应?
- ssl - Erlang ssl:私钥的密码选项
- php - Google 阻止从子域发送邮件
- opencart2.x - Opencart 中的 Summernote 2x
- python - 在 Airflow 中创建 5 个 bash 运算符
- c# - 实体框架关键问题