繁体   English   中英

使用散景将图例定位在绘图区域外

[英]Position the legend outside the plot area with Bokeh

我正在按照此处找到的示例制作绘图

不幸的是,我需要显示 17 条曲线,并且图例与它们重叠。 我知道我可以创建一个图例对象,可以像这里一样显示在绘图区域之外,但我有 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)

我想扩展 joelostbloms 的答案。 也可以从现有绘图中提取图例,并在绘图创建后将其添加到其他位置。

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)

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

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)

在此处输入图片说明

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

为图形设置 plot_height 或高度的位置如下:

p = figure(height=400)

但是图例是在 Despee1990 的回答中创建的,然后放置在图下方,如下所示:

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

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

如果位置更改为右侧:

p.add_layout(legend, 'right')

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

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

即:

p = figure()

或者如果 Legend 所需高度 = 800 且字形所需高度为 400:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM