3

I am trying to use the hover tool using the Bokeh package. I have a pandas data frame with columns named 'Wealth_Gap', 'Infant_Mortality' and 'country'. I would like to plot the values for Infant_Mortality and Wealth_Gap with the country name used in the hover tool.

My code is the following:

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

data = {
    'Wealth_Gap': [30.5, 27.9, 34.2],
    'Infant_Mortality': [3.0, 3.2, 2.3],
    'country': ['Austria', 'Belgium', 'Cyprus']
}

infant_mort_wealth_gap = pd.DataFrame(data,
    columns=['Wealth_Gap', 'Infant_Mortality', 'country'])

source = ColumnDataSource(data=dict(
    x = infant_mort_wealth_gap['Wealth_Gap'],
    y = infant_mort_wealth_gap['Infant_Mortality'],
    desc = infant_mort_wealth_gap['country']
))

p = figure( title='Infant mortality vs wealth gap', 
x_axis_label='Wealth gap', y_axis_label='Infant mortality')

hover = HoverTool()

hover.tooltips = [
    ("index", "$index"),
    ("(x,y)", "($x, $y)"),
    ("desc", "@desc")
]

p.circle('x', 'y', size=20, source=source)

p.tools.append(hover)

show(p)

This gives the following error:

TypeError: Object of type 'DataFrame' is not JSON serializable

I thought it would only take x, y and the hover values as a list. So I have tried the following:

a = infant_mort_wealth_gap['Wealth_Gap'].tolist()
b = infant_mort_wealth_gap['Infant_Mortality'].tolist()

c = infant_mort_wealth_gap['country'].astype(str)
c = c.tolist()

and assigned as follows:

x = a; y = b; desc = c

but this returns the same error.

I have also had a look online and used this: Solved: Python Bokeh Hover Tool giving: AttributeError: unexpected attribute 'tooltips' to Figure but still cannot solve it.

Any help would be great, cheers.

3
  • Can you simplify the code, add some lines that create dummy data, so that we can run it without having access to your data?
    – skalet
    Commented Oct 18, 2018 at 13:36
  • Yes, of course. Sorry, I should have put that in. Commented Oct 18, 2018 at 13:39
  • 1
    Your code runs correctly, thus the real input you are using, not the mock one you provided, is most likely the culprit. This type of error is normally solved by calling the method .to_json() on the pandas dataframe
    – Daneel R.
    Commented Oct 18, 2018 at 15:02

1 Answer 1

2

I don't get any error when running your code sample. For me a tab in my standard browser pops up with an image as shown below.


Edit: Worth nothing is that this is the result after the author added some dummy data and import statements to the code sample so that the problem became reproducible. Thus, as mentioned in the comments by Daniel R. the problem probably lies in the real data.


The result

Not the answer you're looking for? Browse other questions tagged or ask your own question.