首页 > 解决方案 > pandas + bokeh - 如何获取悬停工具的数据框列名称

问题描述

我从数据框的某些列中绘制线条。我希望悬停工具显示源自该数据的列的名称以及未绘制的其他列的一些信息。

例如,在下面的代码中,当鼠标悬停在 A 线上的中心点上时,我希望悬停工具显示“Name = A; Aux = 0.1”。该值存储在 A1 列中。相反,当在 B 线上的中心点上方时,工具应显示“Name = B; Aux = 0.3”

from bokeh.io import show
from bokeh.models import  HoverTool, ColumnDataSource
from bokeh.plotting import figure
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3], 'A' : [1, 5, 3], 'A1': [0.2, 0.1, 0.2],
                  'B' : [2, 4, 3], 'B1':[0.1, 0.3, 0.2]})

tools_to_show = 'box_zoom,save,hover,reset'
p = figure(plot_height =300, plot_width = 1200, 
           toolbar_location='above',
           tools=tools_to_show)

columns = ['A', 'B']
source = ColumnDataSource(df)
for col in columns:
    p.line('x', col, source=source)

hover = p.select(dict(type=HoverTool))
hover.tooltips = [("Name","@col"), ("Aux", "@col1")]
hover.mode = 'mouse'

show(p)

谢谢!

标签: pythonpython-3.xpandasbokeh

解决方案


最近有一个功能可以支持这一点。使用 Bokeh0.13.0或更新版本,您可以name在字形上设置 ,并在工具提示中使用$name. 此外,您可以使用@$name. 但是,“间接”列必须是 中指定的列name,因此您必须重新排列列名以符合此期望:

from bokeh.io import show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3], 'A_y' : [1, 5, 3], 'A': [0.2, 0.1, 0.2],
                  'B_y' : [2, 4, 3], 'B':[0.1, 0.3, 0.2]})

tools_to_show = 'box_zoom,save,hover,reset'
p = figure(plot_height =300, plot_width = 1200,
           toolbar_location='above', tools=tools_to_show,

           # "easy" tooltips in Bokeh 0.13.0 or newer
           tooltips=[("Name","$name"), ("Aux", "@$name")])

columns = ['A', 'B']
source = ColumnDataSource(df)
for col in columns:

    # have to use different colnames for y-coords so tooltip can refer to @$name
    p.line('x', col + "_y", source=source, name=col)

show(p)

在此处输入图像描述


推荐阅读