散景:HoverTool()ColumnDataSource显示???使用@时

时间:2019-02-24 11:09:00

标签: python bokeh

我想向ColumDataSource()添加工具提示,以使其贴近最近的数据点。但是使用@x, @y时会显示???而不是最接近的值。 不过,使用$x, $y可以正常工作。

下面提供了一个示例:

from bokeh.plotting import show, figure, ColumnDataSource
from bokeh.models import HoverTool

a = [x for x in range(10)]
b = [x for x in range(10)]
c = [0.5 * x for x in range(10)]

source = ColumnDataSource(data=dict(a=a, b=b, c=c))

p = figure()
p.line(x='a', y='b', source=source)
p.line(x='a', y='c', source=source)

p.add_tools(HoverTool(
    tooltips=[
        ('index', '$index'),
        ('($x, $y)', "($x, $y)"),
        ('(@x, @y)', "(@x, @y)"),
        ('(@a, @b, @c)', "(@a, @b, @c)")],
    line_policy='nearest',
    mode='mouse'))

show(p)

结果

enter image description here

当我直接通过列表时,它可以正常工作...

在具有两个图形的图形中,我只想显示当前悬停图形的最近值。因此,使用@b, @c不是我想要的。


更新

图中有两个图形,我只想显示悬停的图形的y轴值。

我想要的结果是:

enter image description here

但是在这种情况下,我直接传递了列表对象:

p.line(a, b)
p.line(a, c)

p.add_tools(HoverTool(
    tooltips=[
        ('index', '$index'),
        ('(@x, @y)', "(@x, @y)")],
    line_policy='nearest',
    mode='vline'))

使用ColumnDataSource()时,我必须使用变量的名称,并且不能使用@y指向y轴。

因此,我获得了以下结果:

enter image description here

p.line(x='a', y='b', source=source)
p.line(x='a', y='c', source=source)

p.add_tools(HoverTool(
    tooltips=[
        ('index', '$index'),
        ('(@x, @y)', "(@x, @y)"),
        ('@a', '@a'),
        ('@b', '@b'),
        ('@c', '@c')],
    line_policy='nearest',
    mode='vline'))

“悬停工具”不只显示悬停图形的y轴值。它显示了两个(@b and @c)的值。

2 个答案:

答案 0 :(得分:0)

您必须在ColumnDataSource中设置要显示的值。我不太了解您要显示的内容,但是我将粘贴Bokeh中的示例代码,您可以在页面中找到该代码。 基本上,“ x”和“ y”是要绘制的变量,下一个是要显示的变量。

# Make the ColumnDataSource: source
source = ColumnDataSource(data={
    'x'       : data.loc[1970].fertility,
    'y'       : data.loc[1970].life,
    'country' : data.loc[1970].Country,
})

# Create the figure: p
p = figure(title='1970', x_axis_label='Fertility (children per woman)', 
y_axis_label='Life Expectancy (years)',plot_height=400, plot_width=700,
tools=[HoverTool(tooltips='@country')])

# Add a circle glyph to the figure p
p.circle(x='x', y='y', source=source)

# Output the file and show the figure
output_file('gapminder.html')
show(p) 

答案 1 :(得分:0)

我已经通过将HoverTool()分配给各个renderers来解决了这个问题。

rb = p.line(x='a', y='b', source=source)
rc = p.line(x='a', y='c', source=source)

p.add_tools(HoverTool(
    renderers=[rb],
    tooltips=[
        ('index', '$index'),
        ('(@a, @b)', "(@a, @b)")],
    line_policy='nearest',
    mode='mouse'))

p.add_tools(HoverTool(
    renderers=[rc],
    tooltips=[
        ('index', '$index'),
        ('(@a, @c)', "(@a, @c)")],
    line_policy='nearest',
    mode='mouse'))
相关问题