2

bokehのbox select機能を使って選択したデータの情報を取得する方法を教えてください。

from bokeh.layouts import gridplot
from bokeh.io import output_notebook, show
from bokeh.plotting import figure, output_file
from bokeh.models import ColumnDataSource
output_notebook()

x = list(range(-20, 21))
y0, y1 = [abs(xx) for xx in x], [xx**2 for xx in x]

# create a column data source for the plots to share
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))

TOOLS = "box_select,lasso_select,help"

# create a new plot and add a renderer
left = figure(tools=TOOLS, width=300, height=300)
left.circle('x', 'y0', source=source)

# create another new plot and add a renderer
right = figure(tools=TOOLS, width=300, height=300)
right.circle('x', 'y1', source=source)

p = gridplot([[left, right]])

show(p)
1

1 件の回答 1

1

bokeh.models.CustomJSクラスを使って、選択したオブジェクトの情報をJavaScriptで取得することができます。

p = gridplot([[left, right]])

from bokeh.models import CustomJS
source.selected.js_on_change('indices', CustomJS(args=dict(s=source), code="""
    const inds = s.selected.indices;
    const d = s.data;
    console.log(inds);
"""))

show(p)

たとえばグラフ上で2個の点を選択すると、選択した点のindexがブラウザのコンソールに出力されます。

画像の説明をここに入力

選択したデータの情報を何らかの形でグラフに反映させたい場合は、以下のドキュメントを参照してください。
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html#customjs-for-selections

またこの方法ではJavaScriptの知識が必要になります。
Pythonのみで完結させたい場合は、bokeh serverを起動する必要があります。
詳細は以下のサイトを参照してください。
https://qiita.com/shotoyoo/items/7f342b2f4b8047a57e29

実行環境

  • Python3.9.7
    • bokeh 2.4.7
    • jupyter 1.0.0
  • Firefox 94.0 (64bit)
  • XUbuntu 18.04

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。