Nat*_*ncy 4 python plot interactive bokeh
我正在尝试使用bokeh和悬停工具进行交互式绘图。
更准确地说,我正在尝试绘制与我在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)
Run Code Online (Sandbox Code Playgroud)
但这根本不起作用,有人可以帮助我吗?非常感谢。
代码中的主要问题是,您为数据源的所有列提供了列表,但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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4461 次 |
| 最近记录: |