Bokeh开发:通过TextInput选中ColumnDataSource对应行及绘图点
实现Bokeh中搜索框联动高亮表格行与绘图点
嘿,你想要的这个搜索联动高亮功能其实不难实现,你提到的source.selected.indices和CustomJS确实是关键!我帮你把代码改好了,直接就能用,咱们来看看具体怎么做:
from random import randint from bokeh.io import output_file, show from bokeh.layouts import gridplot, row from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import DataTable, TableColumn, TextInput from bokeh.plotting import figure # 补上之前缺失的绘图模块导入 search_words = TextInput(title="Search for country") data = dict( x=[randint(0, 100) for i in range(10)], y=[randint(0, 100) for i in range(10)], countries = ["France","Spain","Germany","Italy","Portugal","Poland","Russia","Bulgaria","Sweden","Belgium"] ) source = ColumnDataSource(data) columns = [ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="countries", title="Countries"), ] TOOLS = "pan,wheel_zoom,box_select,reset" fig = figure(plot_width=400, plot_height=400, tools=TOOLS) fig.circle('x', 'y', source=source, size=10, selection_color="red", hover_color="green") data_table = DataTable(source=source, columns=columns, width=400, height=280) # 核心逻辑:自定义JS回调实现搜索联动 callback = CustomJS(args=dict(source=source, input=search_words), code=""" // 获取输入框内容并转为小写,实现不区分大小写搜索 const search_val = input.value.toLowerCase(); const countries = source.data.countries; const matched_indices = []; // 遍历所有国家,收集匹配的行索引 for (let i = 0; i < countries.length; i++) { if (countries[i].toLowerCase().includes(search_val)) { matched_indices.push(i); } } // 更新选中索引,自动同步表格和绘图的高亮状态 source.selected.indices = matched_indices; source.change.emit(); // 强制通知数据源更新,确保组件同步 """) # 给输入框绑定回调:输入内容变化时触发搜索逻辑 search_words.js_on_change('value', callback) p = gridplot([fig],[data_table], toolbar_location = "above") show(row(p, search_words))
关键部分说明:
- 模糊搜索逻辑:把输入内容和国家名都转为小写,用
includes实现模糊匹配,比如输入"fr"会自动匹配"France";如果需要精确匹配,把includes改成===就行。 - 联动高亮原理:
source.selected.indices是Bokeh中控制选中状态的核心属性,只要更新这个数组,DataTable的对应行和绘图上的对应点就会自动高亮(你设置的selection_color="red"会生效)。 - 回调触发时机:通过
js_on_change('value', callback)绑定输入框的内容变化事件,用户每输入一个字符都会自动执行搜索逻辑。
内容的提问来源于stack exchange,提问作者Zwentibold
相关产品推荐
相关产品推荐

