【发布时间】:2018-10-18 13:27:39
【问题描述】:
我正在尝试通过 Bokeh 包使用悬停工具。我有一个熊猫数据框,其中包含名为“Wealth_Gap”、“Infant_Mortality”和“国家”的列。我想用悬停工具中使用的国家名称绘制 Infant_Mortality 和 Wealth_Gap 的值。
我的代码如下:
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)
这会产生以下错误:
TypeError: Object of type 'DataFrame' is not JSON serializable
我认为它只会将 x、y 和悬停值作为一个列表。所以我尝试了以下方法:
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()
并分配如下:
x = a; y = b; desc = c
但这会返回相同的错误。
我也上网查了一下,用了这个:Solved: Python Bokeh Hover Tool giving: AttributeError: unexpected attribute 'tooltips' to Figure,还是解决不了。
任何帮助都会很棒,干杯。
【问题讨论】:
-
您能否简化代码,添加一些创建虚拟数据的行,以便我们可以在不访问您的数据的情况下运行它?
-
是的,当然。抱歉,我应该把它放进去。
-
您的代码运行正确,因此您使用的真实输入,而不是您提供的模拟输入,很可能是罪魁祸首。这种类型的错误是normally solved通过在pandas数据帧上调用方法
.to_json()