使用悬停工具在散景中绘制交互式散点图

interactive scatter plot in bokeh with hover tool

我正在尝试使用散景和悬停工具制作交互式绘图。

更准确地说,我正在尝试制作类似 one I made in seaborn 的情节,但我希望它更具互动性,意思是:

我希望人们将鼠标悬停在一个点上时能看到收入水平。

我希望情节保持分散,这样每个点都是一个单独的点,让人们在此过程中悬停在它们上面。

我要挑颜色,划分不同收入水平。

我该怎么做?我试过了:

x = Belgian_income["Municipalities"]
y = Belgian_income["Average income per inhabitant"]

list_x = list(x)
list_y = list(y)

dict_xy = dict(zip(list_x,list_y))

output_file('test.html')
source = ColumnDataSource(data=dict(x=list_x,y=list_y,desc=str(list_y)))
hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("(x,y)", "($x, $y)"),
    ('desc','@desc'),
])

p = figure(plot_width=400, plot_height=400, tools=[hover],
           title="Belgian test")

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

show(p)

但这根本不起作用,有人可以帮助我吗?非常感谢。

代码中的主要问题是您为数据源的所有列提供了列表,desc 除外 - 您在那里提供了一个字符串。 修复后,您的代码就可以工作了。但工具提示显示鼠标指针的 X 和 Y 坐标 - 而不是实际数据。对于实际数据,您必须将悬停工具提示定义中的 $ 替换为 @

考虑这个工作示例:

from math import sin
from random import random

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, HoverTool, LinearColorMapper
from bokeh.palettes import plasma
from bokeh.plotting import figure
from bokeh.transform import transform

list_x = list(range(100))
list_y = [random() + sin(i / 20) for i in range(100)]
desc = [str(i) for i in list_y]

source = ColumnDataSource(data=dict(x=list_x, y=list_y, desc=desc))
hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("(x,y)", "(@x, @y)"),
    ('desc', '@desc'),
])
mapper = LinearColorMapper(palette=plasma(256), low=min(list_y), high=max(list_y))

p = figure(plot_width=400, plot_height=400, tools=[hover], title="Belgian test")
p.circle('x', 'y', size=10, source=source,
         fill_color=transform('y', mapper))

output_file('test.html')
show(p)