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.
.to_json()
on the pandas dataframe