Python Bokeh-如果缺少值,则不显示工具提示
我正在制作一个显示集群活动的博克图。当用户将鼠标悬停在特定处理器上时,我希望它显示处理器的统计信息。代码如下:Python Bokeh-如果缺少值,则不显示工具提示,python,tooltip,bokeh,Python,Tooltip,Bokeh,我正在制作一个显示集群活动的博克图。当用户将鼠标悬停在特定处理器上时,我希望它显示处理器的统计信息。代码如下: TOOLTIPS = [ ("Usage", "@{usage}%"), ("Name", "@name"), ("PID", "@pid"), ("Command", "@command"), ("User", "@user"), ] p = figure(title="Cluster Activity", plot_w
TOOLTIPS = [
("Usage", "@{usage}%"),
("Name", "@name"),
("PID", "@pid"),
("Command", "@command"),
("User", "@user"),
]
p = figure(title="Cluster Activity",
plot_width=1200,
plot_height=700,
x_range=nodes,
y_range=list(reversed(cores)),
tools='hover',
toolbar_location=None,
tooltips=TOOLTIPS
)
这是可行的,但我不想显示值为None的工具提示。例如,如果特定处理器的用户值为“无”,则工具提示不应包含用户值,而应显示“用户:?”
有没有办法做到这一点?在教程中我似乎找不到类似的内容。我希望避免编写自定义JS。我看到两种方法: 1。使用Python并使用多个悬停工具检查Name是否为None 由于HoverTool是一个bokeh.models.tools,您可以通过
p.add_tools(hovertool)
因此,您可以创建两个HoverTool实例,并将数据拆分为两个数据源:
p = figure(title="Cluster Activity",
plot_width=1200,
plot_height=700,
toolbar_location=None)
without = p.square(name="without", ##your filtered data source without names)
with = p.square(name="with", ##your filtered data source with names)
hoverwith = HoverTool(names=["with"],tooltips=TOOLTIPS = [
("Usage", "@{usage}%"),
("Name", "@name"),
("PID", "@pid"),
("Command", "@command"),
("User", "@user"),
])
hoverwithout = HoverTool(names=["without"],tooltips=TOOLTIPS = [
("Usage", "@{usage}%"),
("PID", "@pid"),
("Command", "@command"),
("User", "@user"),
])
p.add_tools(hoverwith, hoverwithout)
使用HoverTool的names属性,可以指定为哪个glyps渲染悬停。我还没有测试代码
2。使用自定义JS(为了完整起见仅提及)
如果您有许多可能丢失的值的不同组合,我只将JS视为实现这一点的一种方法,请看这里:您还可以使用附加到
HoverTool
的JS回调动态创建工具提示(Bokeh 1.1.0)
由于下面的注释,我检查了Bokeh v2.1.1的代码,在修改回调后,它似乎仍然有效:
code = ''' if (cb_data.index.indices.length > 0) {
const index = cb_data.index.indices[0];
const counts = source.data.user[index]
if (counts != null) {
hover.tooltips = [["Name", "@name"], ["User", "@user"], ["PID", "@pid"]];
}
else {
hover.tooltips = [["Name", "@name"], ["PID", "@pid"]];
}
} '''
结果:
这已经不起作用了<代码>常量必须添加到每个已定义变量的前面。但即便如此,当工具提示被更新时,当鼠标悬停在相应的Bart上时,它们不再显示。这就是为什么我总是在我的答案中添加Bokeh版本。哈哈,的确如此,但似乎你是整个互联网上唯一一个回答了这个问题的人。因此,我将这个问题与github中的一个bug联系起来,希望不久有人会回答:看到更新的codeBokeh在向后兼容性方面充满了惊喜。我只看到在原始版本中工具提示被渲染了两次,而在新版本中它只被渲染了一次。如果第一次渲染时间过长,可能会干扰第二次渲染,我们将无法看到它。
code = ''' if (cb_data.index.indices.length > 0) {
const index = cb_data.index.indices[0];
const counts = source.data.user[index]
if (counts != null) {
hover.tooltips = [["Name", "@name"], ["User", "@user"], ["PID", "@pid"]];
}
else {
hover.tooltips = [["Name", "@name"], ["PID", "@pid"]];
}
} '''