在 Bokeh 中显示选择的文本注释

Show text annotations on selection in Bokeh

我有一个带有数据点和相关文本标签的散景图。我想要的是文本标签仅在用户 selects 使用框 select 工具指向时出现。这让我很接近:

from bokeh.plotting import ColumnDataSource,figure,show

source = ColumnDataSource(
    data=dict(
        x=test[:,0],
        y=test[:,1],
        label=[unquote_plus(vocab_idx[i]) for i in range(len(test))]))

TOOLS="box_zoom,pan,reset,box_select"
p = figure(plot_width=400, plot_height=400,tools=TOOLS)
p.circle(x='x',y='y', size=10, color="red", alpha=0.25,source=source)

renderer = p.text(x='x',y='y',text='label',source=source)

renderer.nonselection_glyph.text_alpha=0.

show(p)

这很接近,因为如果我在一些点周围画一个框,那些文本标签会显示出来,其余的会被隐藏,但问题是它会渲染所有文本标签开始(这不是我想要的)想)。初始图应该隐藏所有标签,并且它们应该只出现在 box_select.

我想我可以先用 alpha=0.0 渲染所有东西,然后设置一个 selection_glyph 参数,像这样:

...
renderer = p.text(x='x',y='y',text='label',source=source,alpha=0.)
renderer.nonselection_glyph.text_alpha=0.
renderer.selection_glyph.text_alpha=1.
...

但这会引发错误:

AttributeError: 'NoneType' object has no attribute 'text_alpha'

尝试访问 selection_glyphtext_alpha 属性时。

我知道我可以在此处使用悬停效果或类似效果,但需要将标签默认设置为不可见。另一种但不理想的解决方案是使用切换按钮来打开和关闭标签,但我也不确定该怎么做。

我做错了什么?

从版本0.11.1开始,selection_glyph的值默认为None。这被 BokehJS 解释为 "don't do anything different, just draw the glyph as normal"。所以你需要实际创建一个selection_glyph。有两种方法可以做到这一点,都在此处进行了演示:

http://docs.bokeh.org/en/latest/docs/user_guide/styling.html#selected-and-unselected-glyphs

基本上是

手工

创建一个实际的 Circle 散景模型,例如:

selected_circle = Circle(fill_alpha=1, fill_color="firebrick", line_color=None)
renderer.selection_glyph = selected_circle

使用字形方法参数

或者,为方便起见,Figure.circle 接受像 selection_fill_alphaselection_color 这样的参数(基本上任何行或填充或文本 属性,前缀为 selection_ ) :

p.circle(..., selection_color="firebrick")

然后会自动创建一个Circle用于renderer.selection_glyph


希望这是有用的信息。如果是这样,它强调有两种可能的方法可以改进该项目:

  • 将文档更新为明确并突出显示 renderer.selection_glyph 默认为 None

  • 更改代码,使 renderer.selection_glyph 默认只是 renderer.glyph 的副本(这样您的原始代码就可以工作)

两者的范围都很小,非常适合新贡献者。如果您有兴趣提出一个 Pull Request 来完成这些任务中的任何一个,我们(和其他用户)当然会感谢您的贡献。在这种情况下,请先在

上提出问题

https://github.com/bokeh/bokeh/issues

引用了此讨论,我们可以提供更多详细信息或回答任何问题。