我喜欢使用 HoverTool 设置基本的悬停反馈是多么容易,但我正在努力解决显示的几个方面。我有时间序列数据,测量值以美元表示。此数据以 pandas.Series
的形式开始。清晰的绘图很容易(以下假设使用 jupyter notebook):
p = figure(title='Example currency', x_axis_type='datetime',
plot_height=200, plot_width=600, tools='')
p.line(my_data.index, my_data)
p.yaxis[0].formatter = NumeralTickFormatter(format='$0,0')
show(p)
这显示了时间序列,x 轴上的日期格式和 y 轴值看起来像“$150,000”、“$200,000”、“$250,000”等。我有两个关于 的问题HoverTool
行为:
- 控制
$x
和$y
的格式设置。 - 访问光标下的数据集的名称。
只需添加一个 HoverTool
即可让我查看值,但单位无用:
p.add_tools(HoverTool())
具有这些默认值的相应工具提示值显示“1.468e+5”而不是“$146,800”(甚至是“146800”,底层 Series
值);同样,日期值显示为“1459728000000”而不是(比如)“2016-04-04”。我可以通过将我的 pandas.Series
变成 ColumnDataSource
并添加具有所需格式的字符串列来手动解决此显示问题:
# Make sure Series and its index have `name`, before converting to DataFrame
my_data.name = 'revenue'
my_data.index.name = 'day'
df = my_data.reset_index()
# Add str columns for tooltip display
df['daystr'] = df['day'].dt.strftime('%m %b %Y')
df['revstr'] = df['revenue'].apply(lambda x: '${:,d}'.format(int(x)))
cds = ColumnDataSource(df)
p = figure(title='Example currency', x_axis_type='datetime',
plot_height=200, plot_width=600, tools='')
p.line('day', 'revenue', source=cds)
p.yaxis[0].formatter = NumeralTickFormatter(format='$0,0')
p.add_tools(HoverTool(tooltips=[('Amount', '@revstr'), ('Day', '@daystr')]))
show(p)
但是有没有办法在 HoverTool
配置中处理格式?这似乎比上面要求的所有数据集转换更可取。我查看了文档并(快速)扫描了源代码,没有看到任何明显的东西可以避免我像上面那样构建“输出”列。
与此相关,当我在一个图中有几行时,我有什么方法可以访问每行的 name
(或者可能是 legend
值)在 HoverTool.tooltips
中?在工具提示中包含一些内容以区分来自哪些数据集值,而不是需要依赖(比如)线条颜色和工具提示显示,这将非常有帮助。现在,我已经在 ColumnDataSource
中添加了一个额外的列,这就是我想要显示的字符串值;这显然只适用于包含单个测量列的数据集。当多行共享底层 ColumnDataSource
时,访问提供给 y
的列名就足够了。
最佳答案
嘿,我知道它晚了 2 年,但这是给遇到这个问题的其他人的
p.add_tools(HoverTool(
tooltips=[
('Date', '@Date{%F}'),
('Value', '@Value{int}')],
formatters={
'Date':'datetime',
'Value':'numeral'},mode='vline'
))
关于python - 在 HoverTool 中格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669719/