在我的例子中,我收集了水果和蔬菜的数据。数据本身具有相同的键值,即名称和值。
当用户更改下拉列表时,我想换出条形图中的数据以显示下拉列表选项。我怎样才能做到这一点。我对如何在自定义回调中管理所有这些感到有些迷茫。
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider, Select
from bokeh.plotting import figure, output_file, show
from bokeh.models.glyphs import VBar
import pandas as pd
# create dataframes of data
df_fruit = pd.DataFrame({
'values':[3, 5, 12, 21, 16],
'names':['Apples', 'Pears', 'Nectarines', 'Grapes', 'Strawberries']
})
source_fruit = ColumnDataSource(df_fruit)
df_vegetables = pd.DataFrame({
'values':[3, 4, 4],
'names':['Peppers', 'Potatoes', 'Carrots']
})
source_vegetables = ColumnDataSource(df_vegetables)
# plot dataframes
names = df_fruit['names'].tolist()
plot = figure(plot_width=500, plot_height=400, title="Data Counts", x_range=names)
plot.vbar(source=source_fruit, x="names", top="values", bottom=0, width=0.75, color="red", fill_alpha=0.7, name='fruits')
# callback for input controls
callback = CustomJS(args=dict(source=source_fruit), code="""
var data = source.data;
console.log(data);
source.change.emit();
""")
ui_view = Select(title="View", callback=callback, value="Fruit", options=["Fruit", "Vegetables"])
callback.args['ui_view'] = ui_view
# layout
layout = column(ui_view, plot)
show(layout)
答案 0 :(得分:1)
使用分类范围时,将忽略与当前范围中的类别不对应的字形值。鉴于此,简单的事情就是在前面“绘制”两个数据集,然后在回调中更改范围:
# plot dataframes
names = df_fruit['names'].tolist()
plot = figure(plot_width=500, plot_height=400, title="Data Counts", x_range=names)
fruit = plot.vbar(source=source_fruit, x="names", top="values", bottom=0, width=0.75, color="red", fill_alpha=0.7, name='fruits')
veg = plot.vbar(source=source_vegetables, x="names", top="values", bottom=0, width=0.75, color="red", fill_alpha=0.7, name='veg')
# callback for input controls
callback = CustomJS(args=dict(fruit=fruit, veg=veg, plot=plot), code="""
if (ui_view.value=="Fruit") {
plot.x_range.factors = fruit.data_source.data.names
} else {
plot.x_range.factors = veg.data_source.data.names
}
""")
ui_view = Select(title="View", callback=callback, value="Fruit", options=["Fruit", "Vegetables"])
callback.args['ui_view'] = ui_view
# layout
layout = column(ui_view, plot)
show(layout)