无法将 Bokeh 中的 CrossHairTool 链接到多个图

在我的实现中,十字准线仅在悬停的情节中显示。我目前正在使用 Bokeh 版本2.1.1和 Python Anaconda 版本3.7.6,使用 VSCode 版本 1.48 中的 Python 扩展。我不熟悉 Javascript,因此欢迎任何有助于调试我的代码以正确显示跨两个图的十字准线的帮助。

我的代码:

# Importing libraries:

import pandas as pd

import random

from datetime import datetime, timedelta

from bokeh.models import CustomJS, CrosshairTool, ColumnDataSource, DatetimeTickFormatter, HoverTool

from bokeh.layouts import gridplot

from bokeh.plotting import figure, output_file, show


# Function wrote by Hamid Fadishei to enable a linked crosshair within gridplot:

def add_vlinked_crosshairs(figs):

    js_leave = ''

    js_move = 'if(cb_obj.x >= fig.x_range.start && cb_obj.x <= fig.x_range.end &&\n'

    js_move += 'cb_obj.y >= fig.y_range.start && cb_obj.y <= fig.y_range.end){\n'

    for i in range(len(figs)-1):

        js_move += '\t\t\tother%d.spans.height.computed_location = cb_obj.sx\n' % i

    js_move += '}else{\n'

    for i in range(len(figs)-1):

        js_move += '\t\t\tother%d.spans.height.computed_location = null\n' % i

        js_leave += '\t\t\tother%d.spans.height.computed_location = null\n' % i

    js_move += '}'

    crosses = [CrosshairTool() for fig in figs]

    for i, fig in enumerate(figs):

        fig.add_tools(crosses[i])

        args = {'fig': fig}

        k = 0

        for j in range(len(figs)):

            if i != j:

                args['other%d'%k] = crosses[j]

                k += 1

        fig.js_on_event('mousemove', CustomJS(args=args, code=js_move))

        fig.js_on_event('mouseleave', CustomJS(args=args, code=js_leave))


慕盖茨4494581
浏览 159回答 1
1回答

繁花如伊

这是一个适用于 Bokeh 2.2.1 的解决方案:只需对所有需要它链接的图使用相同的十字准线工具对象。像这样:import numpy as npfrom bokeh.plotting import figure, showfrom bokeh.layouts import gridplotfrom bokeh.models import CrosshairToolplots = [figure() for i in range(6)][plot.line(np.arange(10), np.random.random(10)) for plot in plots]linked_crosshair = CrosshairTool(dimensions="both")for plot in plots:    plot.add_tools(linked_crosshair)show(gridplot(children=[plot for plot in plots], ncols=3))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python