我正在研究一个显示集群活动的散景图。当用户将鼠标悬停在特定处理器上时,我希望它显示有关处理器的统计信息。下面是代码:
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的工具提示。例如,如果某个特定处理器的User值为None,则工具提示不应包含用户值,而不是显示“User:???”。
有没有办法做到这一点?我似乎无法在教程中找到类似的内容。我想避免编写自定义JS。
您还可以使用附加到HoverTool
(Bokeh 1.1.0)的JS回调动态创建工具提示
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool, CustomJS
pid = [1, 2, 3, 4, 5, 6]
user = ['user1', 'user2', 'user3', 'user4', None, 'user6']
name = ['name', 'name2', 'name3', 'name4', 'name5', 'name6']
source = ColumnDataSource(data = dict(pid = pid, user = user, name = name))
p = figure(x_range = FactorRange(*name), sizing_mode = 'stretch_both', title = "Test", toolbar_location = None, tools = "")
p.vbar(x = 'name', top = 'pid', width = 0.2, source = source)
code = ''' hover.tooltips = [["Name", "@name"], ["PID", "@pid"]];
if (cb_data.index.indices.length > 0) {
index = cb_data.index.indices[0];
counts = source.data.user[index]
if (counts != null)
hover.tooltips = [["Name", "@name"], ["User", "@user"], ["PID", "@pid"]];
} '''
hover = HoverTool()
hover.callback = CustomJS(args = dict(source = source, hover = hover), code = code)
p.add_tools(hover)
show(p)
结果:
我看到两种方法:
1.使用Python检查Name是否为None并使用多个HoverTool
由于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作为一种方法来做这个,看看这里:https://groups.google.com/a/continuum.io/forum/#!msg/bokeh/4VxEbPaLqnA/-qYLDsbZAwAJ