在Bokeh中为Spans添加悬停工具标签?

6
我知道您可以使用Label()函数向图表添加自定义标签,但是您必须指定(x,y)坐标来放置标签。
我有一些时间序列数据的注释,正在使用Span()添加到图表中,但我真正想要的是如果我可以将标签添加到这些Span注释中,每当您悬停在Span对象上时就会显示出来。这似乎是一件简单的事情,但我真的很困惑。
这是我一直在研究的示例代码:
p = figure(x_axis_type='datetime', y_axis_type='datetime', tools='hover')

p.line(daylight_warsaw_2013.Date,daylight_warsaw_2013.Sunset, line_dash='solid', line_width=2, legend="Sunset")
p.line(daylight_warsaw_2013.Date,daylight_warsaw_2013.Sunrise, line_dash='dotted', line_width=2, legend="Sunrise")


annotations = {
    'start':{'timestamp':dt(2013, 3, 31,2,0,0),'desc':"start of daylight savings time"},
    'end':{'timestamp':dt(2013, 10, 27, 3, 0, 0),'desc':"end of daylight savings time"}
}

def auto_annotate(df,plot):
    for row in df.values(): 
        xloc = time.mktime(row['timestamp'].timetuple())*1000 
        span = Span(location=xloc, dimension='height', line_width=2, line_dash='dashed',line_color='green')
        label = Label(x=xloc, y=5000000, text=row['desc'])
        plot.add_layout(label)
        plot.add_layout(span)

auto_annotate(annotations,p)
show(p)

请记住,我不知道如何使用JavaScript。

1个回答

3
考虑到您评论说不知道如何使用JS,我提出以下解决方案作为实现您想要的可能方式。
from bokeh.io import show, output_notebook
from bokeh.plotting import figure

from bokeh.core.properties import value
from bokeh.models import Span, HoverTool

output_notebook()

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 4, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="")

p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,
             legend=[value(x) for x in years])

constant_line = [2.5, 2.5, 2.5, 2.5, 2.5, 2.5]
partial = p.line(fruits, constant_line, line_width=0.01, line_color='green', line_dash='dashed')

p.add_tools(HoverTool(renderers = [partial],tooltips=[("Value Constant", str(constant_line[0]))]))

daylight_savings_start = Span(location=2.5,
                              dimension='width', line_color='green',
                              line_dash='dashed', line_width=3)
p.add_layout(daylight_savings_start)


p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
show(p)

你可以在仅安装bokeh的jupyter笔记本上直接运行上一个代码。
问题是,如果你只画一条线,它并不会从负无穷延伸到正无穷。

enter image description here

如果在该行添加一个Span,您将得到以下结果。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接