Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am having a problem using the Bokeh package in python

Tags:

python

bokeh

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.

like image 619
Alexander Caskie Avatar asked Feb 16 '26 04:02

Alexander Caskie


1 Answers

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

like image 51
skalet Avatar answered Feb 17 '26 16:02

skalet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!