【问题标题】:Button widget adds new plots instead of replacing the old one按钮小部件添加新图而不是替换旧图
【发布时间】:2020-10-18 16:14:30
【问题描述】:

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

我想添加按钮以在单击时前进或后退一步。 这在下面的代码中实现。我的问题是,当我从on_button_ 内部回调原始函数myplot 时,它会再次绘制所有内容,但我只想要更新的散点图。

如您所见,我已经尝试过 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()

【问题讨论】:

    标签: python matplotlib jupyter-notebook ipywidgets


    【解决方案1】:

    通过删除plt.show()plt.close()并改写display(fig)clear_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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多