首页 > 解决方案 > 按钮小部件添加新图而不是替换旧图

问题描述

我有一个使用小部件的功能,它工作得很好,但是滑块有点难以小步移动。

我想添加按钮以在单击时前进或后退一步。这在下面的代码中实现。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()

标签: pythonmatplotlibjupyter-notebookipywidgets

解决方案


通过删除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)

推荐阅读