我有以下代码:
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.plotting import figure, output_file, show
if __name__ == '__main__':
year = [1960, 1970, 1980, 1990, 2000, 2010]
pop_pakistan = [44.91, 58.09, 78.07, 107.7, 138.5, 170.6]
pop_india = [449.48, 553.57, 696.783, 870.133, 1000.4, 1309.1]
output_file('line.html', mode='inline')
plot = figure(title='Population Graph of India and Pakistan', x_axis_label='Year',
y_axis_label='Population in million')
source1 = ColumnDataSource(data=dict(
year=year,
population=[pop_pakistan, pop_india],
))
print(source1.data)
hover = HoverTool()
hover.tooltips = """
<div style=padding=5px>Data</div>
"""
plot.add_tools(hover)
plot.line(year, pop_pakistan, line_width=2, line_color='green', legend='Pakistan')
plot.circle(year, pop_pakistan, fill_color="green", line_color='green', size=8)
plot.line(year, pop_india, line_width=2, line_color='orange', legend='India')
plot.circle(year, pop_india, fill_color="orange", line_color='orange', size=8)
show(plot)
我想显示悬停数据。我收到以下警告
BokehUserWarning: ColumnDataSource's columns must be of the same length. Current lengths: ('population', 2), ('year', 6)
如何将Hovertool用于多个Y轴?
谢谢
更新
根据@bigreddot的回答,我进行了以下更改:
plot.line('year', 'pop_pakistan', line_width=2, line_color='green', legend='Pakistan', source=source)
plot.circle('year', 'pop_pakistan', fill_color="green", line_color='green', size=8, source=source)
plot.line('year', 'pop_india', line_width=2, line_color='orange', legend='India', source=source)
plot.circle('year', 'pop_india', fill_color="orange", line_color='orange', size=8, source=source)
show(plot)
但是我无法显示相应国家/地区的相关悬停数据。
答案 0 :(得分:1)
该消息是因为from typing import Callable
def bar(b: str, func: Callable[[str], int])->int:
return func(b)
中列的长度不完全相同。 ColumnDataSource
是类似于熊猫ColumnDataSource
的表格结构。存在不同长度的列是没有意义的。就您而言,您有:
DataFrame
和
year = [1960, 1970, 1980, 1990, 2000, 2010] # length 6
大概是您想要的:
population = [pop_pakistan, pop_india] # length 2
这将创建一个由三列组成的CS,长度均为6。
然后,下一个观察结果是您正在创建CDS,但从未真正使用过它。要使用数据源,您必须将其实际传递给字形函数,并按名称引用列,例如
source = ColumnDataSource(data=dict(
year=year,
pop_pakistan=pop_pakistan,
pop_india=pop_india
))
最后,您的工具提示说明不执行任何操作,除了始终打印相同的文本# pass the source argument and refer to columns by name (strings)
plot.line('year', 'pop_pakistan', source=source, ...)
plot.circle('year', 'pop_pakistan, source=source, ...)
plot.line('year', 'pop_india', source=source, ...)
plot.circle('year', 'pop_india', source=source, ...)
之外,什么也不做。通常,您可能希望使用"Data"
语法来显示数据源中的值,例如@
或在工具提示文字内的某处“ @pop_india”。有关更多信息,请参见HoverTool documenatation。