带有悬停工具的Bokeh线图

1 投票
1 回答
4029 浏览
提问于 2025-04-18 18:12

我想在一个折线图或散点图中使用Bokeh的HoverTool。下面是代码(大部分内容来自http://docs.bokeh.org/docs/gallery/correlation.html)。在我的例子中,Hover只显示“acme”这条线的信息,我不知道怎么才能让它也能显示另一条线“choam”的信息。有没有什么建议或解决方案?

from numpy import cumprod, linspace, random
import time
from bokeh.plotting import *
from bokeh.objects import GridPlot, HoverTool

num_points = 20

now = time.time()
dt = 24*3600 
dates = linspace(now, now + num_points*dt, num_points)
acme = cumprod(random.lognormal(0.0, 0.04, size=num_points))
choam = cumprod(random.lognormal(0.0, 0.04, size=num_points))

output_file("correlation.html", title="correlation.py example")

source = ColumnDataSource(
    data=dict(
        acme=acme,
        choam=choam,
        dates=dates
    )
)

figure(x_axis_type = "datetime", tools="hover,pan,wheel_zoom,box_zoom,reset,previewsave")

hold()

line(dates, acme, color='#1F78B4', legend='ACME')
line(dates, choam, color='#FB9A99', legend='CHOAM')

scatter(dates, acme, color='#1F78B4', source = source, fill_color=None, size=8)
scatter(dates, choam, color='#33A02C', fill_color=None, size=8)

curplot().title = "Stock Returns"
grid().grid_line_alpha=0.3


hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0]
hover.tooltips = OrderedDict([
    ('Price', "@acme"),
    ('Price', "@choam"),
    ('Date', "@dates"),
    ('Date', "@dates"),
])

show() 

1 个回答

1

在0.8版本中,我用类似这样的代码来画多个图:

source1 = ColumnDataSource(
    data=dict(
        acme=acme,
        dates=dates
    )
)

source2 = ColumnDataSource(
    data=dict(
        choam=choam,
        dates=dates
    )
)

scatter(dates, acme, color='#1F78B4', source = source1, fill_color=None, size=8)
scatter(dates, choam, color='#33A02C', source = source2, fill_color=None, size=8)

不能保证以后还会这样用——我还在等线条的提示信息呢 :)

撰写回答