LoginSignup
1
0

bokeh: 特定のGlyphRendererにカーソルを当てたときのみツールチップを表示させる

Posted at

環境

  • Python 3.12.1
  • bokeh 3.4.0

背景

以下のコードで散布図をプロットしました。

sample.py
from bokeh.io import output_file, save
from bokeh.plotting import figure, ColumnDataSource

data = {"a": [1, 2, 3], "b": [3, 1, 2], "name":["aaaaaaaaaaaa", "bbbbbbbbbbbb", "cccccccccccc"]}
source = ColumnDataSource(data)
TOOLTIPS = [
    ("a", "@a"),
    ("b", "@b"),
    ("name", "@name"),
]
fig = figure(width=300, height=300, tooltips=TOOLTIPS)

fig.scatter(
    source=source,
    x="a",
    y="b",
)
fig.text(
    source=source,
    x="a",
    y="b",
    text="name"
)
output_file("output.html")
save(fig)

プロットした円形にカーソルを当てたときに、ツールチップを表示させています。
テキストにカーソルを当てたときにもツールチップが表示されます。今回の例だとnameが長いので、ツールチップの表示領域が広くなり、ツールチップの表示が鬱陶しく感じました。

散布図1.gif

したがって、テキストにカーソルを当てたときはツールチップを表示させないようにしたいです。

解決策

HoverToolインスタンスのrenderersプロパティに対して、scatter()の戻り値を設定することで、円形にカーソルを当てたときのみツールチップが表示されるようになりました。

fig = figure(width=300, height=300)

scatter_renderer = fig.scatter(
    source=source,
    x="a",
    y="b",
)
text_renderer = fig.text(source=source, x="a", y="b", text="name")

hover_tool = HoverTool(tooltips=TOOLTIPS)
hover_tool.renderers = [scatter_renderer]
fig.add_tools(hover_tool)

上記のコードは以下を参考にしました。

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