写下散景图选择的数据不起作用

问题描述 投票:1回答:1

我正在尝试从散景图中编写选定的数据点。想法是访问ColumnDataSource selected属性,以便在点击Button时获取所选数据点。

下面是我想要实现的功能模型。

期望:单击“选定点”按钮后,将创建一个包含所选点列表(如果有)的文件/tmp/datapoints.json

现实:没有/tmp/datapoints.json

from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import ColumnDataSource, Button
from bokeh.layouts import column

# setup plot
fig = figure(title='Select points',
            plot_width=300, plot_height=200)

import numpy as np
x = np.linspace(0,10,100)
y = np.random.random(100) + x

import pandas as pd
data = pd.DataFrame(dict(x=x, y=y))

# define data source
src = ColumnDataSource(data)

# define plot
fig.circle(x='x', y='y', source=src)

# define interaction
def print_datapoints(attr, old, new):
    with open('/tmp/datapoints.json', 'w') as f:
        import json
        json.dump(src.selected, f)

btn = Button(label='Selected points', button_type='success')
btn.on_click(print_datapoints)

curdoc().add_root(column(btn,fig))

我错过了什么?

谢谢。

python bokeh
1个回答
1
投票

使用lasso_select工具,您可以像这样工作:

from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, Button
from bokeh.layouts import column

# setup plot
tools = "pan,wheel_zoom,lasso_select,reset"
fig = figure(title='Select points',
            plot_width=300, plot_height=200,tools=tools)

import numpy as np
x = np.linspace(0,10,100)
y = np.random.random(100) + x

import pandas as pd
data = pd.DataFrame(dict(x=x, y=y))

# define data source
src = ColumnDataSource(data)

# define plot
fig.circle(x='x', y='y', source=src)

# define interaction
def print_datapoints():
    indices=src.selected['1d']['indices']
    results=data.iloc[indices]
    resultsDict=results.to_dict()['x']
    resultString=str(resultsDict)
    with open('tmp/datapoints.json', 'w') as f:
        import json
        json.dump(resultString, f)

btn = Button(label='Selected points', button_type='success')
btn.on_click(print_datapoints)

curdoc().add_root(column(btn,fig))

为了使json.dump工作,我必须从'/tmp/datapoints.json'中删除第一个'/'。

© www.soinside.com 2019 - 2024. All rights reserved.