使用 Bokeh 将图例定位在绘图区域之外

Position the legend outside the plot area with Bokeh

我正在按照找到的示例制作情节 here

不幸的是,我有 17 条曲线需要显示,图例与它们重叠。我知道我可以创建一个可以显示在绘图区域外的图例对象,如 here,但我有 17 条曲线,因此使用循环更方便。

你知道如何结合这两种方法吗?

好的,我找到了解决方案。请参阅下面的代码,我刚刚修改了交互式图例示例:

import pandas as pd
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, IBM, MSFT, GOOG
from bokeh.models import Legend
from bokeh.io import output_notebook

output_notebook()

p = figure(plot_width=800, plot_height=250, x_axis_type="datetime", toolbar_location='above')
p.title.text = 'Click on legend entries to mute the corresponding lines'

legend_it = []

for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    c = p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8,
           muted_color=color, muted_alpha=0.2)
    legend_it.append((name, [c]))


legend = Legend(items=legend_it)
legend.click_policy="mute"

p.add_layout(legend, 'right')

show(p)

也可以将图例放置在自动分组的、间接创建的图例的绘图区域之外。诀窍是创建一个空图例,并在使用字形 legend_group 参数之前使用 add_layout 将其放置在绘图区域之外:

from bokeh.models import CategoricalColorMapper, Legend
from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers


color_mapper = CategoricalColorMapper(
    factors=[x for x in flowers['species'].unique()], palette=Category10[10])
p = figure(height=350, width=500)
p.add_layout(Legend(), 'right')
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color=dict(field='species', transform=color_mapper))
show(p)

我想详细说明 joelostblom 的回答。 也可以从现有情节中提取图例并添加 创建情节后的其他地方。

from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers


# add a column with colors to the data
colors = dict(zip(flowers['species'].unique(), Category10[10]))
flowers["color"] = [colors[species] for species in flowers["species"]]

# make plot
p = figure(height=350, width=500)
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color="color")
p.add_layout(p.legend[0], 'right')

show(p)

作为上述答案的关于可见性的说明虽然有用,但没有看到我成功地将图例放在图下方,其他人也可能会遇到这个问题。

图中的plot_height或高度设置如下:

p = figure(height=400)

但图例是按照 Despee1990 的回答创建的,然后放置在图下方:

legend = Legend(items=legend_it)
p.add_layout(legend, 'below')

然后不显示图例,也不显示情节。

如果位置改到右边:

p.add_layout(legend, 'right')

...然后图例仅显示在项目适合图形绘图高度的位置。 IE。如果您的地块高度为 400,但图例需要 800 的高度,那么您将看不到不适合该地块区域的项目。

要解决此问题,请完全删除图中的绘图高度或指定足以包含图例项框高度的高度。

即或者:

p = figure()

或者如果 Legend 要求高度 = 800 并且字形要求高度为 400:

p = figure(plot_height=800)
p.add_layout(legend, 'below')