我正在努力通过使用Bokeh在Jupyter Notebook中进行交互式绘图。我想绘制一张世界地图,并显示一些数据随时间的变化。我成功制作了一个图并使用了滑块来调整年份,但是当我更改滑块时,滑块值将不会更新。滑块的代码如下:
#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 refreshing plot中的解决方案,但仍然遇到了同样的错误。
散景小部件(如滑块)在jupyter笔记本中不起作用(至少,并非不使用某些javascript)。正如documentation所说:
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的提示,您将需要使用bokeh服务器,否则here中讨论的Jupyter交互器讨论中的某些功能。