python - Bokeh - 如果它有缺失值,则不显示工具提示

标签 python tooltip bokeh

我正在制作一个显示集群事件的 Bokeh 图。当用户将鼠标悬停在特定处理器上时,我希望它显示有关处理器的统计信息。继承人的代码:

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, FactorRange

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)

由于下面的评论,我检查了 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"]];
                }                                     
            } '''

结果:

enter image description here

关于python - Bokeh - 如果它有缺失值,则不显示工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679754/

相关文章:

python - 为什么 "if letter in dict"在 Python 中运行错误?

javascript - 相对于响应式页面的 SVG 元素重新定位工具提示

javascript - 将数组中的附加值添加到工具提示

javascript - jQuery 工具提示定位问题

python - Bokeh 不显示 Pandas 情节

python - 运行时钟和触发

python - 理解元组计算

python - Bokeh 'utf8' 编解码器无法解码字节 0xe9 : unexpected end of data

python - Holoviews散点图的回归线?

python - 格式化 NumPy 数组中的日期数据