2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bokeh: 折れ線の円形マーカーを表示/非表示切り替える

Last updated at Posted at 2022-07-11

環境

  • Python 3.12.1
  • bokeh 3.4.1

やりたいこと

Pythonのbokehライブラリを使って、以下のようなコードで、円形のマーカー付き折れ線グラフを作成しています。

import bokeh
from bokeh.plotting import figure, output_file, save

output_file("graph.html")

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

fig = figure(x_axis_label="x", y_axis_label="y")

fig.line(x, y)
fig.scatter(x, y)

save(fig)

image.png

やりたいこと

プロット数が多くなると、マーカーが邪魔になる場合があります。
そこで、チェックボックスを使ってマーカーの表示/非表示を切り替えられるようにします。

解決方法

circle関数の戻り値に対して、glyph.radius0にすれば、円形は表示されなくなります。

import bokeh
from bokeh.plotting import figure, output_file, save
from bokeh.models import CustomJS, CheckboxGroup, GlyphRenderer


def create_checkbox(scatter: GlyphRenderer) -> CheckboxGroup:
    checkbox_group = CheckboxGroup(labels=["折れ線のマーカーを表示する"], active=[0])
    args = {"scatter": scatter}
    code = """
        let size = ( "0" in this.active) ? 4 : 0
        scatter.glyph.size = size
    """
    checkbox_group.js_on_change("active", CustomJS(code=code, args=args))
    return checkbox_group


output_file("graph.html")

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

fig = figure(x_axis_label="x", y_axis_label="y")

fig.line(x, y)
scatter = fig.scatter(x, y, size=4)
checkbox = create_checkbox(scatter)
save([fig, checkbox])

マーカー表示非表示.gif

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?