python - 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)
谢谢!
解决方案
最近有一个功能可以支持这一点。使用 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)
推荐阅读
- node.js - 如何通过 mocha 设置 npm 测试?
- java - SQLite DELETE 查询在 moveToFirst() 上冻结
- java - 在每个 if & else if & else 语句中都有 return 与在代码末尾有一个 return
- c++ - 如何在 setuptools.Extension 中使用 C++ 头文件?
- javascript - 为什么输出显示未定义,我该如何摆脱它?
- azure - 如何使用 Azure DevOps API 获取工作项的外部链接列表?
- javascript - 如何在 try/catch 短语中循环,并在 Javascript 中成功呈现在浏览器上?
- reactjs - 忽略来自反应钩子返回数组的值 -
- java - 运行我的 JAR 时无法从外部文件读取对象()
- r - 如何用变量填充子集参数?