如何获取Bokeh热力图点击位置的X、Y标签?
解决Bokeh热力图点击获取X/Y标签的问题
我明白你现在的困扰——点击热力图只能拿到坐标,想要的X/Y标签却拿不到,cb_data还没有效信息。其实问题出在你没用到数据源的选中索引来获取自定义字段,下面给你一步步解决:
核心原因
Bokeh的TapTool(你应该用的是这个点击工具)默认的cb_obj是工具本身,cb_data也不会自动包含你存在ColumnDataSource里的xname、yname这类自定义字段。真正能拿到对应数据的是数据源的selected.indices属性——点击矩形时,这个属性会记录下你点击的那个矩形对应的数据源行索引。
修改后的回调代码
把你原来的回调换成下面这个,就能直接拿到X/Y标签和其他自定义数据了:
from bokeh.models import CustomJS, ColumnDataSource, TapTool, figure # 假设你的xname、yname等数据已经准备好 source = ColumnDataSource(data=dict( xname=xname, yname=yname, colors=color, alphas=alpha, means=means.flatten(), stds=stds.flatten(), )) # 关键:通过选中索引获取标签 callback = CustomJS(args=dict(source=source), code=""" const selectedIndices = source.selected.indices; // 确保有选中的元素 if (selectedIndices.length > 0) { const idx = selectedIndices[0]; const xLabel = source.data.xname[idx]; const yLabel = source.data.yname[idx]; // 还能顺便拿到你存在数据源里的均值、标准差 const meanValue = source.data.means[idx]; alert(`点击位置信息:X标签=${xLabel}, Y标签=${yLabel}, 均值=${meanValue}`); } """) # 创建图表并绑定TapTool回调 p = figure(title="Plot", x_axis_location="above", tools="tap") # 用rect绘制热力图(确保x、y参数和数据源的xname、yname对应) p.rect( x='xname', y='yname', width=1, height=1, fill_color='colors', fill_alpha='alphas', source=source ) # 把回调绑定到TapTool上 tap_tool = p.select_one(TapTool) tap_tool.callback = callback
额外说明
- 如果需要支持多选(比如按住Shift点击多个矩形),只需要循环遍历
selectedIndices数组里的所有索引就行。 - 确保你的
rect组件的x和y参数直接用了数据源里的xname、yname,这样点击时选中的索引才会和标签一一对应。
内容的提问来源于stack exchange,提问作者Fedor Nikitin
相关产品推荐
相关产品推荐

