python - 在输入更改时更改散景数据源
问题描述
在我的示例中,我收集了水果和蔬菜的数据。数据本身具有相同的键值,即名称和值。
当用户更改下拉列表时,我想换出条形图中的数据以显示下拉列表选项。我怎样才能做到这一点。我对如何在自定义回调中管理所有这些有点迷茫。
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)
解决方案
使用分类范围时,与当前范围中的类别不对应的字形值将被忽略。鉴于此,要做的最简单的事情就是预先“绘制”两个数据集,然后在回调中更改范围:
# 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)
推荐阅读
- java - 计算给定特定日期和时间的分钟时差
- vue.js - Vue.js 不同的符号
- typescript - 如何在打字稿中键入此对象?
- python - Pygamezero 代码,我的代码在我没有任何代码的情况下工作,这是为什么呢?:
- terminal - grep 命令未读取此 adb 命令的命令输出
- swagger-ui - Swagger UI 进入 dropwizard
- embedded-linux - qemu-system-arm 难以启动 zImage
- javascript - app.post 不适用于根路由以外的任何路由
- flutter - 带有 SingleChildScrollView、Column、TabBar 和 TabBarView 的 Scaffold 中的高度问题
- sql - 从列值 varchar SQL 中提取数据类型