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

如何在Python中使用Lasso Select选择并存储数据点?Bokeh存储问题求助

解决Bokeh套索选择无法存储选中数据点的问题

我刚搞定过类似的场景,你遇到的核心问题其实是CustomJS只能在浏览器端运行JavaScript,没法直接调用Python代码或者修改Python环境里的变量。下面给你两个最实用的解决方案,根据你的部署场景选:

方案1:用Bokeh Server(推荐,最直接)

如果你的项目可以用Bokeh Server运行(这是Bokeh官方推荐的交互式应用模式),那就能直接在Python里处理选中事件,轻松存储数据。

步骤&代码示例

  1. 编写Bokeh Server应用,给数据源绑定Python回调函数,监听selected属性变化
  2. 在回调里提取选中的索引,对应到原始数据,然后存储(比如存到变量、本地文件、数据库都可以)
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
import pandas as pd

# 模拟你的业务数据
data = pd.DataFrame({
    'x': [1, 2, 3, 4, 5, 6],
    'y': [2, 4, 1, 5, 3, 6],
    'label': ['A', 'B', 'C', 'D', 'E', 'F']
})
source = ColumnDataSource(data)

# 创建图表并开启套索选择工具
p = figure(title="Lasso Selection Demo", tools="lasso_select")
p.circle(x='x', y='y', source=source, size=10)

# 存储选中数据的容器(可替换为文件/数据库操作)
selected_data_list = []

def on_lasso_selected(attr, old, new):
    # 获取选中数据的索引
    selected_indices = new.indices
    if selected_indices:
        # 提取对应的数据行
        selected_data = data.iloc[selected_indices]
        print("本次选中的数据:")
        print(selected_data)
        # 存储数据,示例存到列表,你可以改成写入CSV或数据库
        selected_data_list.append(selected_data)
        # 比如写入CSV:selected_data.to_csv("selected_points.csv", mode='a', header=False)

# 给数据源绑定选中事件的Python回调
source.on_change('selected', on_lasso_selected)

# 将图表加入Bokeh Server文档
curdoc().add_root(p)

运行方式

在终端执行以下命令启动服务:

bokeh serve --show your_script.py

之后每次用套索选点,Python后端都会自动触发回调,直接处理并存储选中的数据。

方案2:静态HTML + Python后端(适合不能用Bokeh Server的场景)

如果你的需求是生成静态HTML页面,那得用CustomJS把选中的数据通过AJAX发送到Python后端(比如Flask/Django接口),由后端负责存储。

前端CustomJS代码示例

from bokeh.plotting import figure, output_file, save
from bokeh.models import ColumnDataSource, CustomJS

# 模拟数据
data = {'x': [1,2,3,4,5], 'y': [2,4,1,5,3]}
source = ColumnDataSource(data)

# 创建图表
p = figure(title="Static Lasso Selection", tools="lasso_select")
p.circle(x='x', y='y', source=source, size=10)

# 编写CustomJS,把选中数据发送到Python后端
callback = CustomJS(args=dict(source=source), code="""
    const selectedIndices = source.selected.indices;
    if (selectedIndices.length > 0) {
        // 提取选中的数据
        const selectedData = {
            x: selectedIndices.map(i => source.data.x[i]),
            y: selectedIndices.map(i => source.data.y[i])
        };
        // 用fetch发送POST请求到后端接口
        fetch('http://localhost:5000/save-selected', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(selectedData),
        })
        .then(response => response.json())
        .then(data => console.log('数据存储成功:', data))
        .catch(error => console.error('存储失败:', error));
    }
""")

# 绑定回调到数据源的选中事件
source.selected.js_on_change('indices', callback)

# 生成静态HTML文件
output_file("lasso_static.html")
save(p)

Python后端(Flask示例)

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/save-selected', methods=['POST'])
def save_selected():
    selected_data = request.get_json()
    # 这里可以替换为写入数据库、云存储等逻辑
    with open('selected_points.txt', 'a') as f:
        f.write(f"{selected_data}\n")
    return jsonify({"status": "success", "data": selected_data})

if __name__ == '__main__':
    app.run(debug=True)

使用方式

  1. 先启动Flask后端服务
  2. 打开生成的lasso_static.html页面,用套索选点后,数据会自动发送到后端完成存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:00:32