You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Bokeh图表获取坐标时改编方案遇'inds'未定义错误求助

解决Bokeh框选工具中NameError: name 'inds' is not defined的问题

嘿,我来帮你搞定这个Bokeh的报错问题!你遇到的NameError: name 'inds' is not defined,核心原因很明确:你的代码里直接引用了inds这个变量,但它根本没被定义过——不管是在前端的CustomJS回调里,还是后端的Python回调里,都漏掉了获取选中索引并赋值给inds的关键步骤。

下面分两种常见场景给你具体的修复方案:

场景1:使用前端CustomJS回调

如果你的代码是用CustomJS来处理框选事件,必须先在JS代码里获取选中的索引数组,再赋值给inds,否则JS环境找不到这个变量。示例代码如下:

import pandas as pd
from bokeh.plotting import figure, show
from bokeh.models import CustomJS, ColumnDataSource

# 构造示例数据
df = pd.DataFrame({'x': [1,2,3,4,5], 'y': [2,4,1,3,5]})
source = ColumnDataSource(data=df)

# 正确的CustomJS回调:先定义inds变量
callback = CustomJS(args=dict(source=source), code="""
    // 关键步骤:获取选中的索引并赋值给inds
    const inds = source.selected.indices;
    
    // 提取选中点的x、y坐标
    const selected_x = [];
    const selected_y = [];
    const x_data = source.data['x'];
    const y_data = source.data['y'];
    
    for (let i = 0; i < inds.length; i++) {
        selected_x.push(x_data[inds[i]]);
        selected_y.push(y_data[inds[i]]);
    }
    
    // 这里可以添加后续处理,比如打印到控制台
    console.log('选中的x坐标:', selected_x);
    console.log('选中的y坐标:', selected_y);
""")

# 创建图表并绑定回调
p = figure(tools="box_select,lasso_select")
p.circle('x', 'y', source=source)
source.selected.js_on_change('indices', callback)

show(p)

场景2:使用Bokeh Server的Python回调

如果是用Bokeh Server做后端交互,你需要在Python回调函数里从source.selected.indices获取选中索引,再赋值给inds,不能直接凭空使用这个变量。示例代码如下:

import pandas as pd
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

def modify_doc(doc):
    df = pd.DataFrame({'x': [1,2,3,4,5], 'y': [2,4,1,3,5]})
    source = ColumnDataSource(data=df)
    
    p = figure(tools="box_select,lasso_select")
    p.circle('x', 'y', source=source)

    def selection_callback(attr, old, new):
        # 关键步骤:把选中的索引数组赋值给inds
        inds = new
        # 提取选中点的x、y坐标
        selected_x = [source.data['x'][i] for i in inds]
        selected_y = [source.data['y'][i] for i in inds]
        print('选中的x坐标:', selected_x)
        print('选中的y坐标:', selected_y)
    
    source.selected.on_change('indices', selection_callback)
    doc.add_root(p)

# 启动Bokeh Server
server = Server({'/': Application(FunctionHandler(modify_doc))})
server.start()
server.io_loop.add_callback(server.show, "/")
server.io_loop.start()

简单总结下:你只要补全“获取选中索引并赋值给inds”这一步,这个NameError就会消失啦!

内容的提问来源于stack exchange,提问作者user123328

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:57