使用CustomJS回调在Bokeh中基于下拉列表创建动态悬停工具提示

2024-04-24 17:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Bokeh创建了一个散点图,我非常希望能够根据您在下拉菜单中的选择来更改悬停工具上显示的工具提示。如果选择了“statset1”,我想显示stats1&2。如果选择了“statset2”,我想显示stats3,4,5。在

我希望最终结果是一个html文件,因此使用CustomJS进行回调可能是必须的。这里是我设法得到的代码。问题很可能与回调有关,因为我根本不知道如何通过回调来处理工具提示。在

import pandas as pd
from bokeh.plotting import figure, show
from bokeh.models import CustomJS, ColumnDataSource, HoverTool, ColumnDataSource, Select
from bokeh.layouts import row

#Create a dataframe with x and y coordinates and 4 different statistics
df = pd.DataFrame({
            'x':[1,2,3],
            'y':[1,2,3],
            'stat1':[1,2,3],
            'stat2':[4,5,6],
            'stat3':[7,8,9],
            'stat4':[10,11,12],
            'stat5':[13,14,15]
})

#Create Bokeh's ColumnDataSource
source=ColumnDataSource(data=df)

#Create the different options for the Hovertool tooltips
option1=[('Stat1','@stat1'),
         ('Stat2','@stat2')]

option2=[('Stat3','@stat3'),
         ('Stat4','@stat4'),
         ('Stat5','@stat5')]

#Set the default option for the Hovertool tooltips
hover=HoverTool(tooltips=option1)

#Create the figure
plot = figure(tools=[hover])
plot.circle('x', 'y', source=source)

#Create the callback that will update the tooltips
callback = CustomJS (args=dict(tt=plot.hover), code="""
    if (cb_obj.value='Stat Set 1') {
        tt.tooltips=option1
    } else {
        tt.tooltips=option2
    }
    """)

#Create a dropdown menu that allows you to change which set of stats will populate the tooltips
stat_select=Select(options=['Stat Set 1', 'Stat Set 2'],
                        value='Stat Set 1',
                         title='What stats set do you want to see when you hover?', callback=callback)

show(row(stat_select,plot))

Tags: 工具thefromimportplotcreatecallbackbokeh
1条回答
网友
1楼 · 发布于 2024-04-24 17:29:56

我找到了一个有answer over on the Bokeh Discourse的人。在

plot.hover返回一个列表,因为一个绘图可以有多个工具提示。 因此,与使用tt.tooltips = option1不同的是,tt必须订阅才能使用列表的第一个条目,即tt[0].tooltips = option1。在

options = [option1, option2]

#Create the callback that will update the tooltips

callback = CustomJS (args=dict(tt=plot.hover, opts=options), code="""

if (cb_obj.value=='Stat Set 1') {

    tt[0].tooltips=opts[0]

} else {

    tt[0].tooltips=opts[1]

}

""")

相关问题 更多 >