在Bokeh中,如何将工具提示添加到时间序列图表(悬停工具)?

时间:2015-07-18 23:43:02

标签: python-3.x pandas tooltip bokeh timeserieschart

是否可以将工具提示添加到时间序列图表中?

在下面的简化代码示例中,当鼠标悬停在相关行上时,我希望看到一个列名称('a','b'或'c')。

相反,一个“???”显示并且所有三行都有一个工具提示(而不仅仅是悬停在其上的那个)

enter image description here

根据文件( http://bokeh.pydata.org/en/latest/docs/user_guide/tools.html#hovertool),以“@”开头的字段名称被解释为数据源上的列。

  1. 如何在工具提示中显示pandas数据框中的“列”?

  2. 或者,如果高级TimeSeries接口不支持这个,那么使用低级接口做同样事情的线索是什么? (line?multi_line?)或将DataFrame转换为不同的格式(ColumnDataSource?)

  3. 对于奖励积分,如何格式化“$ x”以将日期显示为日期?

  4. 提前致谢

        import pandas as pd
        import numpy as np
        from bokeh.charts import TimeSeries
        from bokeh.models import HoverTool
        from bokeh.plotting import show
    
        toy_df = pd.DataFrame(data=np.random.rand(5,3), columns = ('a', 'b' ,'c'), index = pd.DatetimeIndex(start='01-01-2015',periods=5, freq='d'))   
    
        p = TimeSeries(toy_df, tools='hover')  
    
        hover = p.select(dict(type=HoverTool))
        hover.tooltips = [
            ("Series", "@columns"),
            ("Date", "$x"),
            ("Value", "$y"),
            ]
    
        show(p)
    

4 个答案:

答案 0 :(得分:13)

以下是我的想法。

它不漂亮但它有效。

我仍然是Bokeh(& Python)的新手,所以如果有人想提出更好的方法,请随意。

enter image description here

import pandas as pd
import numpy as np
from bokeh.charts import TimeSeries
from bokeh.models import HoverTool
from bokeh.plotting import show

toy_df = pd.DataFrame(data=np.random.rand(5,3), columns = ('a', 'b' ,'c'), index = pd.DatetimeIndex(start='01-01-2015',periods=5, freq='d'))       

 _tools_to_show = 'box_zoom,pan,save,hover,resize,reset,tap,wheel_zoom'        

p = figure(width=1200, height=900, x_axis_type="datetime", tools=_tools_to_show)


# FIRST plot ALL lines (This is a hack to get it working, why can't i pass in a dataframe to multi_line?)   
# It's not pretty but it works. 
# what I want to do!: p.multi_line(df)
ts_list_of_list = []
for i in range(0,len(toy_df.columns)):
    ts_list_of_list.append(toy_df.index.T)

vals_list_of_list = toy_df.values.T.tolist()

# Define colors because otherwise multi_line will use blue for all lines...
cols_to_use =  ['Black', 'Red', 'Lime']
p.multi_line(ts_list_of_list, vals_list_of_list, line_color=cols_to_use)


# THEN put  scatter one at a time on top of each one to get tool tips (HACK! lines with tooltips not yet supported by Bokeh?) 
for (name, series) in toy_df.iteritems():
    # need to repmat the name to be same dimension as index
    name_for_display = np.tile(name, [len(toy_df.index),1])

    source = ColumnDataSource({'x': toy_df.index, 'y': series.values, 'series_name': name_for_display, 'Date': toy_df.index.format()})
    # trouble formating x as datestring, so pre-formating and using an extra column. It's not pretty but it works.

    p.scatter('x', 'y', source = source, fill_alpha=0, line_alpha=0.3, line_color="grey")     

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [("Series", "@series_name"), ("Date", "@Date"),  ("Value", "@y{0.00%}"),]
    hover.mode = 'mouse'

show(p)

答案 1 :(得分:6)

我不熟悉Pandas,我只是使用python list来展示如何向muti_lines添加工具提示,显示系列名称以及正确显示日期/时间的示例。结果就是这样。 感谢@bs123's answer

中的@tterry's answerBokeh 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

答案 2 :(得分:1)

这是我的解决方案。我检查了字形渲染数据源,看看它上面有什么名字。然后我在胡佛工具提示上使用这些名称。您可以看到结果图here

public partial class MonitorConfigurationControl : UserControl
{
    private MonitorServer _monitorServer { get; set; }
    public MonitorConfigurationControl()
    {
        InitializeComponent();
    }


    private void MonitorConfigurationControl_Load(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        this.AutoScroll = true;
        this.AutoSize = false;
        this.MinimumSize = this.Size = this.Parent.Size;

        //MessageBox.Show("Test", "Test", MessageBoxButtons.OK);
    }
}

答案 3 :(得分:0)

原始海报的代码不适用于最新的熊猫(DatetimeIndex构造函数已更改),但是Hovertool现在支持formatters属性,可用于将格式指定为strftime字符串。像

fig.add_tool(HoverTool(
    tooltip=[
        ('time', '@index{%Y-%m-%d}')
    ],
    formatters={
        '@index': 'datetime'
    }
))