如何为控制多个散景图添加一个图例?

How to add one legend for that controlls multiple bokeh figures?

如何创建一个图例来控制多个散景图?或者如何自定义使用散景创建的导出 html 文件以添加具有类似功能的图例?

这是场景。我创建了一个包含 4 个不同图形的 html 文件。每个图都有一个带有 labels/names 的图例,表示特定图中显示的各个行。四个图例中的每一个都可以单击以分别切换每个图中的线条。

虽然四幅图各有一个图例,但线条是相关的,所以它们每一行描述的是一件事。

我现在想为所有图形组合成一个图例,以切换所有四个图形中的每一行。

也许有办法以某种方式将这种功能添加到导出的 html 文件中?

我认为更有经验的人知道如何实现这一目标。

提前致谢!

亲切的问候

图例不是(还?)'standalone' 散景模型,它们需要附加到人物身上。现在要为多个图形添加外部图例,并将其放置在布局中的任何位置,需要一些解决方法。

我通常会像下面那样使用 'invisible' 图形保存共享图例。然后您必须手动定义图例项并分配给它们的每个标签和渲染器列表。

from bokeh.io import show
from bokeh.plotting import figure
from bokeh.models import LegendItem, Legend
from numpy.random import random, choice
from bokeh.layouts import gridplot
from webcolors import html4_names_to_hex

del html4_names_to_hex['white']
palette = list(html4_names_to_hex.keys())

fig_list = [figure(plot_width=300,plot_height=300) for i in range(4)]

renderer_list = []
color_list = []
for fig in fig_list:
    for i in range(5):
        color = choice(palette)
        renderer = fig.line(range(10),random(10),line_width=2,color=color)
        renderer_list += [renderer]
        color_list += [color]

# Lines with the same color will share a same legend item
legend_items = [LegendItem(label=color,renderers=[renderer for renderer in renderer_list if renderer.glyph.line_color==color]) for color in set(color_list)]

## Use a dummy figure for the LEGEND
dum_fig = figure(plot_width=300,plot_height=600,outline_line_alpha=0,toolbar_location=None)
# set the components of the figure invisible
for fig_component in [dum_fig.grid[0],dum_fig.ygrid[0],dum_fig.xaxis[0],dum_fig.yaxis[0]]:
    fig_component.visible = False
# The glyphs referred by the legend need to be present in the figure that holds the legend, so we must add them to the figure renderers
dum_fig.renderers += renderer_list
# set the figure range outside of the range of all glyphs
dum_fig.x_range.end = 1005
dum_fig.x_range.start = 1000
# add the legend
dum_fig.add_layout( Legend(click_policy='hide',location='top_left',border_line_alpha=0,items=legend_items) )

figrid = gridplot(fig_list,ncols=2,toolbar_location='left')
final = gridplot([[figrid,dum_fig]],toolbar_location=None)
show(final)