首页 > 解决方案 > 滑块值未更新 Bokeh Python

问题描述

我在 Jupyter Notebook 中使用 Bokeh 制作交互式情节时遇到了困难。我想绘制一张世界地图并显示一些数据随时间的发展。我成功地制作了一个绘图并有一个滑块来调整年份,但是当我更改滑块时,滑块值不会更新。滑块的代码如下:

#creating the data source as a dict
source = ColumnDataSource({
    'x': p_df['x'], 
    'y': p_df['y'], 
    'Country': p_df['Country'], 
    'nkill': p_df['nkill']
})

#making a slider and assign the update_plot function to changes
slider = Slider(start=start_yr, end=end_yr, step=1, value=start_yr, title='Year')
slider.on_change('value',update_plot)

#the update_plot function which needs to run based on the new slider.value
def update_plot(attr, old, new):
    #Update glyph locations
    yr = slider.value
    Amountkills_dt_year = p_df[p_df['Year'] ==yr]
    new_data = {
        'x': Amountkills_dt_year['x'], 
        'y': Amountkills_dt_year['y'], 
        'Country': Amountkills_dt_year['Country'], 
        'nkill': Amountkills_dt_year['nkill']
    }
    source.data = new_data
    #Update colors
    color_mapper = LinearColorMapper(palette='Viridis256',
                                 low = min(Amount_of_Terrorist_Attacks['nkill']),
                                 high = max(Amount_of_Terrorist_Attacks['nkill']))

我想用 update_plot() 函数更新绘图的地方。我尝试了Python bokeh slider not refresh plot中的解决方案,但我仍然遇到了同样的错误。

标签: pythonpython-3.xsliderbokehinteractive

解决方案


像滑块这样的散景小部件在 jupyter 笔记本中不起作用(至少,在不使用一些 JavaScript 的情况下是这样)。正如文档所说:

To use widgets, you must add them to your document and define their functionality. Widgets can be added directly to the document root or nested inside a layout. There are two ways to program a widget’s functionality:

        Use the CustomJS callback (see JavaScript Callbacks). This will work in standalone HTML documents.

        Use bokeh serve to start the Bokeh server and set up event handlers with .on_change (or for some widgets, .on_click).

正如@bigreddot 所暗示的那样,您将需要使用散景服务器,或者可能需要使用此处讨论的 jupyter 交互器讨论中的一些功能。


推荐阅读