首页 > 解决方案 > Bokek 悬停工具显示不正确 | Python

问题描述

我有以下数据框:

Date                   Impressions  Link_Clicks
2017-05-29 00-00-00    1,492,046    8,093
2017-06-05 00-00-00    845,012      4,864
2017-06-12 00-00-00    1,167,100    6,897
2017-06-19 00-00-00    895,781      4,472
2017-06-26 00-00-00    1,037,839    9,518
2017-07-03 00-00-00    1,139,060    9,668
2017-07-10 00-00-00    1,235,760    9,268
2017-07-17 00-00-00    1,200,906    7,989
2017-07-24 00-00-00    1,214,534    6,991
2017-07-31 00-00-00    1,434,225    7,311
2017-08-07 00-00-00    557,393      2,908

我正在尝试使用已成功完成的 Bokeh 来可视化这一点,但是在实现悬停工具时,它会返回专门除以 2 的数字。这是一个错误吗?

使用的库:

from bokeh.io import output_notebook, show, push_notebook
from bokeh.io import output_file, show, curdoc
output_notebook()
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import HoverTool, DatetimeTickFormatter, DataRange1d, CustomJS, Plot, LinearAxis, Grid
from bokeh.charts import Bar, BoxPlot, Donut, HeatMap, Histogram, Line, Scatter, TimeSeries

我的代码可以在下面找到:

source = ColumnDataSource(data=dict(
    desc = bar_df.index,
    y = bar_df["Link_Clicks"],
))

p = Bar(bar_df, label=bar_df.index, values="Link_Clicks", width=1, source=source, agg='sum',
       line_color="white", plot_width=900, plot_height=400, bar_width=0.9, legend=None, toolbar_location="right")

p.add_tools(HoverTool(tooltips=[("Link_Clicks", "@y{1.11}"),
                                ("Date", "@index")]))

p.xaxis.major_label_orientation = 45

show(p)

注意:如果你尝试复制这个,Bokeh 的日期不能是 DateTime 格式;只有字符串。

快速转换:df["Date"] = df["Date"].apply(lambda x: str(x).replace(':','-'))

在此处输入图像描述

当悬停在上面时,你可以看到它被 2 完美分割,这很奇怪。我尝试在 ColumnDataSource 下和悬停工具中将 y*2 相乘,但仍然没有运气。

有任何想法吗?

标签: pythongraphdata-visualizationbokeh

解决方案


对于那些研究这个问题的人,由于托比指出我正确的方向,我已经解决了。我尝试了一个更简单的数据集,但它适用于我尝试过的所有内容。见下文:

数据:

bokeh_bar = df.groupby(["Audience"], as_index=False)["Impressions"].sum()

Index       Audience    Impressions
0           Core        23725548
1           Homepage    14163811
2           LAL_10%     18277859
3           LAL_3%      14879857
4           Page_1      4406266

代码:

    source = ColumnDataSource(data=dict(audience=list(bokeh_bar["Audience"]), 
                                    impressions=list(bokeh_bar["Impressions"]), 
                                    color=Spectral6))

p = figure(x_range=list(bokeh_bar["Audience"]), plot_width=900, plot_height=300, title="Impressions by Audience",
           toolbar_location=None, tools="")

p.vbar(x='audience', top='impressions', width=0.9, color='color', 
       legend="audience", source=source)

p.add_tools(HoverTool(tooltips=[("Audience", "@audience"), ("Impressions", "@impressions")]))

p.xgrid.grid_line_color = None
p.legend.orientation = "horizontal"
p.legend.location = ('top_right')
p.legend.label_text_font_size = '8pt'

show(p)

结果:

在此处输入图像描述

希望这会有所帮助。悬停工具也会返回正确的数字。


推荐阅读