我试图在散景图中设置窗口小部件对象和图表对象之间的交互。我想绘制仅针对从选择菜单中选择的一个类别过滤的聚合条形图。我使用的是python v2.7和bokeh v0.12.0
图表显示但是当我在select_obj菜单中更改值并且我不知道原因时,图表上的值没有变化。
我试图从this post
实施解决方案以下示例代码:
import pandas as pd
import numpy as np
from bokeh.io import output_file, show
from bokeh.layouts import column, widgetbox
from bokeh.models import CustomJS
from bokeh.models.sources import ColumnDataSource
from bokeh.charts import Bar
from bokeh.models.widgets import Select
df = pd.DataFrame({'cat_1' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'cat_2' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'val' : np.random.randn(8)})
source = ColumnDataSource(df)
source.remove('index')
original_source = ColumnDataSource(df)
original_source.remove('index')
# barchart
bar = Bar(source.data, values='val', label='cat_1', stack='cat_1', agg='sum',
title="Title", plot_width=400)
# select widget
select_obj = Select(title="Category:", value="one", options=df['cat_2'].unique().tolist())
# callback
callback_code = """
var data = source.get('data');
var original_data = original_source.get('data');
var menu_val = menu_select_obj.get('value');
for (var key in original_data) {
data[key] = [];
for (var i = 0; i < original_data['cat_2'].length; ++i) {
if (original_data[cat_2'][i] === menu_val) {
data[key].push(original_data[key][i]);
}
}
}
menu_select_obj.trigger('change');
"""
callback = CustomJS(
args=dict(source=source,
original_source=original_source,
menu_select_obj=select_obj,
target_obj=bar),
code=callback_code)
# connect the callbacks to the filter widgets
select_obj.callback = callback
# layout
layout = column(widgetbox(select_obj), bar)
output_file("example.html")
show(layout)