在 Python 的 Jupyter Notebook 中,如何在拖动 ipywidgets 交互功能中的滑块时停止闪烁?

How to stop flickering while dragging the slider in interact feature of ipywidgets in Jupyter notebook in Python?

我写了一个函数来按特定顺序显示条形图。该函数将需求作为参数。

代码如下所示:

def display_plot(demand = 0):
    
    plt.figure(figsize = (20, 10))
    
    x = ["A","B","C","D","E","F","G","H"]
    y = [-25, -10, 5, 10, 30, 40, 50, 60]
    w = [300, 200, 205, 400, 200, 400, 540, 630]
    w_cumulative = [300, 500, 705, 1105, 1305, 1705, 2245, 2875]

    colors = ["yellow","limegreen","green","blue","red","brown","grey","black"]

    xpos = [150.0, 400.0, 602.5, 905.0, 1205.0, 1505.0, 1975.0, 2560.0]

    fig = plt.bar(xpos,
            height = y,
            width = w,
            color = colors,
            alpha = 0.5,
          )
    
    #For loop to get the cutoff value 
    for index in range(len(w_cumulative)):

        if w_cumulative[index] < demand:
            pass

        else:
            cut_off_index = index
            print (cut_off_index)
            break

    plt.hlines(y = y[cut_off_index],
          xmin = 0,
          xmax = demand,
          color = "red",
          linestyle = "dashed")
        
    plt.xlim((0, w_cumulative[-1]))

    plt.vlines(x = demand,
              ymin = 0,
              ymax = y[cut_off_index])
    
    plt.text(x = demand - 5,
            y = y[cut_off_index]+5,
            s = str(y[cut_off_index]))

    plt.show()
    

我尝试与此功能创建的情节进行交互。这里的自定义特征是demand。当我更改需求时,hlines 和 vlines 会相应更改。以及显示每个条形高度的文本。

正在使用

from ipywidgets import *
interact(display_plot, demand = (0, sum(w), 10))

我得到了想要的输出,如图所示

当我点击滑块上的某个点来更改值时,它比较好。但是,当我拖动滑块时,情节会闪烁很多。这很烦人。我认为这是因为我在 display_plot 函数中使用了 for-loop,它计算 cut_off_index 的瞬时值,同时通过拖动滑块更改 demand

我尝试通过从 from IPython.display import clear_output 调用在 display_plot() 函数中添加 clear_output(wait=True)。我还尝试在函数中添加 time.sleep(1) 。但是拖动滑块的时候剧情还是闪烁很多。情节的高度总是不变的。但是我交互的时候只需要更新里面的内容。在这种情况下有什么办法可以避免闪烁的情节吗?

好的。这帮助我避免了闪烁。

我使用了以下代码进行交互输出:

demand = widgets.IntSlider(value = 10,
                          min = 0, 
                          max = sum(w),
                          step = 10,
                          description = "Demand",
                          continuous_update = False)

interactive_plot = interact(display_plot,
                           demand = demand)