In Bokeh, how do I add tooltips to a Timeseries chart (hover tool)?

前端 未结 4 1459
半阙折子戏
半阙折子戏 2020-12-08 14:03

Is it possible to add Tooltips to a Timeseries chart?

In the simplified code example below, I want to see a single column name (\'a\',\'b\' or \'c\') when the mouse

4条回答
  •  一生所求
    2020-12-08 14:33

    I’m not familiar with Pandas,I just use python list to show the very example of how to add tooltips to muti_lines, show series names ,and properly display date/time。Below is the result. Thanks to @bs123's answer and @tterry's answer in Bokeh Plotting: Enable tooltips for only some glyphs

    my result

    # -*- coding: utf-8 -*-
    
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.models import  HoverTool
    from datetime import datetime
    
    dateX_str = ['2016-11-14','2016-11-15','2016-11-16']
    #conver the string of datetime to python  datetime object
    dateX = [datetime.strptime(i, "%Y-%m-%d") for i in dateX_str]
    
    v1= [10,13,5]
    v2 = [8,4,14]
    v3= [14,9,6]
    v = [v1,v2,v3]
    
    names = ['v1','v2','v3']
    colors = ['red','blue','yellow']
    
    output_file('example.html',title = 'example of add tooltips to multi_timeseries')
    tools_to_show = 'hover,box_zoom,pan,save,resize,reset,wheel_zoom'
    p = figure(x_axis_type="datetime", tools=tools_to_show)
    
    #to show the tooltip for multi_lines,you need use the ColumnDataSource which define the data source of glyph
    #the key is to use the same column name for each data source of the glyph
    #so you don't have to add tooltip for each glyph,the tooltip is added to the figure
    
    #plot each timeseries line glyph
    for i in xrange(3):
    # bokeh can't show datetime object in tooltip properly,so we use string instead
        source = ColumnDataSource(data={
                    'dateX': dateX, # python datetime object as X axis
                    'v': v[i],
                    'dateX_str': dateX_str, #string of datetime for display in tooltip
                    'name': [names[i] for n in xrange(3)]
                })
        p.line('dateX', 'v',source=source,legend=names[i],color = colors[i])
        circle = p.circle('dateX', 'v',source=source, fill_color="white", size=8, legend=names[i],color = colors[i])
    
        #to avoid some strange behavior(as shown in the picture at the end), only add the circle glyph to the renders of hover tool
        #so tooltip only takes effect on circle glyph
        p.tools[0].renderers.append(circle)
    
    # show the tooltip
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [("value", "@v"), ("name", "@name"), ("date", "@dateX_str")]
    hover.mode = 'mouse'
    show(p)
    

    tooltips with some strange behavior,two tips displayed at the same time

提交回复
热议问题