LoginSignup
1
0

More than 1 year has passed since last update.

Bokeh 凡例クリックにカスタムイベントを登録する

Posted at

Pythonのグラフライブラリ BokehのTIPSです。

凡例クリックで、関連するグラフを一斉に表示させたり、非表示にしたりしたいことありますよね。
ですがBokehでは、凡例にカスタムイベントを直接登録することはできなさそうでした。

解決法を探したところ、スタックオーバーフローにありました。
プロット(Renderer)の表示非表示の状態変化には、カスタムイベントが登録できるようです。

簡単な例ですが、以下のような感じです。

from bokeh.plotting import figure, save
from bokeh.layouts import gridplot
from bokeh.models import CustomJS

p1 = figure(width=400, height=200)
p2 = figure(width=400, height=200)

r1 = p1.circle([1, 2, 3], [5, 3, 1], legend_label='main')
r2 = p2.line([1, 2, 3], [3, 1, 5])

# 凡例へのクリックポリシーの指定は、プロットを作成した後でないと正常に動かない
p1.legend.click_policy = 'hide'

# プロットr1の表示非表示の状態に対し、カスタムイベントを付与する
r1.js_on_change(
    'visible',
    CustomJS(
        args=dict(r2=r2),  # r2をJavaScriptに渡す
        code='r2.visible = !(r2.visible);'))  # JavaScriptでr2の表示状態を反転する

save(gridplot([p1, p2], ncols=1), filename='test.html')

Screen-recording-2022-07-05-23.56.09.gif

狙い通り動きました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0