2
votes

My goal is to create a bokeh Bar chart which represents a histogram. Ideally I'd like to have hovertooltips enabled so that hovering over a column will show the total cumulative value at that point.

My original dataframe looks something like this:

           Buckets     Data1_%   Data2_%
0  (0.0166, 0.283]  16.886842 17.242004
1      (0.3, 0.32]   1.111779  1.284348

In order for me to make my bar plot with side by side views of Data1_% and Data2_%, I needed to call pd.melt() in the following manner:

df_temp = pd.melt(df, id_vars = "Buckets", value_vars = ["Data1_%", "Data2_%"])

which then makes the dataframe look like this:

           Buckets    variable      value
0   (0.0166, 0.283]    Data1_%  16.886842
1       (0.3, 0.32]    Data1_%   1.111779

where "variable" contains "Data1_%" or "Data2_%" as the two possible items.

Finally, I generate my plot and attempt to graph it in this manner:

bar = Bar(df_temp, label = "Buckets", values = "value", group = "variable")
bar.add_tools(HoverTool(tooltips = [("TestValue", "@value")]))
show(bar)

The bar graph renders fine and looks like this: enter image description here

which is exactly what I want! The hover tool is enabled and does work, but it always shows "???" as the value, meaning it isn't pulling from my dataframe (df_temp) as I thought I would.

Ideally it would show two datapoints: the value of the "variable" field and also of the "value" field.

So for my first data point, I would hope for it to show:

Variable: Data1_% Value: 16.886842

and so on. But I would be happy just getting the value parameter to work.

Any tips would be greatly appreciated! I've tried reading documentation about changing my dataframe to a ColumnDataSource and other such tricks, but I would really appreciate seeing some code about how I can make this work.

Thanks!

EDIT: Quick follow up question. How can I enforce ordering on my BokehChart as well? I would like data to show up in the same order that I have it listed in my dataframe, but it appears that Bokeh garbles up these values at times and spits things out in a seemingly random order. I thought Bokeh was supposed to be very easy to use with Dataframes!

1

1 Answers

1
votes

The old bokeh.charts, including Bar was deprecated and subsequently removed. To create a histogram in Bokeh (with tooltip) you should use the stable bokeh.plotting API. There are a variety of possible ways to do this, but here is one complete example created with Bokeh 0.13.0:

import numpy as np
from bokeh.plotting import figure, show

measured = np.random.normal(0, 0.5, 1000)
hist, edge = np.histogram(measured, density=True, bins=50)

p = figure(tooltips="top: @top")
p.quad(top=hist, bottom=0, left=edge[:-1], right=edge[1:], line_color="white")

show(p)

enter image description here