interactive scatter plot in bokeh with hover tool

依然范特西╮ 提交于 2021-02-07 12:52:27

问题


I'm trying to make a an interactive plots with bokeh and the hover tool.

More precisely, I'm trying to make a plot like the one I made in seaborn but I'd like it to be more interactive, meaning :

I'd like people to see the income level when they hover over one point.

I'd like the plot to stay scattered like that such thas each point is an individual point, letting people hover over them in the process.

I'd like to pick the colors,to divide between different levels of income.

How would I do that ? I tried this :

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)

But it doesn't work at all, can someone help me ? Thanks a lot.


回答1:


The main issue in your code is that you provide lists to all columns of the data source, except for the desc - you provide a single string there. With that fixed, your code works. But the tooltips show X and Y coordinates of the mouse pointer - not the actual data. For the actual data, you have to replace $ in the hover tooltips definitions with @.

Consider this working example:

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)


来源:https://stackoverflow.com/questions/49833824/interactive-scatter-plot-in-bokeh-with-hover-tool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!