散景位置图例外的绘图区域为堆叠的vbar

问题描述 投票:0回答:2

我在Bokeh中有一个堆积条形图,其简化版本可以通过以下方式复制:

from bokeh.plotting import figure
from bokeh.io import show

months = ['JAN', 'FEB', 'MAR']
categories = ["cat1", "cat2", "cat3"]
data = {"month" : months,
        "cat1"  : [1, 4, 12],
        "cat2"  : [2, 5, 3],
        "cat3"  : [5, 6, 1]}
colors = ["#c9d9d3", "#718dbf", "#e84d60"]

p = figure(x_range=months, plot_height=250, title="Categories by month",
           toolbar_location=None)
p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)

show(p)

我想在图表中添加一个图例,但我的真实图表在堆栈中有很多类别,因此图例会非常大,所以我希望它在右边的绘图区域之外。

有一个SO答案here解释了如何在绘图区域之外添加图例,但在给定的示例中,每个渲染的字形都被分配给一个变量,然后将其标记并添加到Legend对象中。我知道如何做到这一点,但我相信vbar_stack方法在一次调用中创建多个字形,所以我不知道如何标记这些并将它们添加到单独的Legend对象以放置在图表区域之外?

或者,在调用legend然后在图表区域外找到图例时,是否有更简单的方法来使用vbar_stack参数?

任何帮助非常感谢。

python legend bokeh
2个回答
1
投票

对于任何感兴趣的人,现在使用vbar_stack字形的简单索引修复此问题。方案如下:

from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import Legend

months = ['JAN', 'FEB', 'MAR']
categories = ["cat1", "cat2", "cat3"]
data = {"month" : months,
        "cat1"  : [1, 4, 12],
        "cat2"  : [2, 5, 3],
        "cat3"  : [5, 6, 1]}
colors = ["#c9d9d3", "#718dbf", "#e84d60"]

p = figure(x_range=months, plot_height=250, title="Categories by month",
           toolbar_location=None)
v = p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)

legend = Legend(items=[
    ("cat1",   [v[0]]),
    ("cat2",   [v[1]]),
    ("cat3",   [v[2]]),
], location=(0, -30))

p.add_layout(legend, 'right')

show(p)

1
投票

感谢Toby Petty的回答。

我稍微改进了您的代码,以便它自动从源数据中抓取类别并分配颜色。我认为这可能很方便,因为类别通常没有明确存储在变量中,必须从数据中获取。

from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import Legend
from bokeh.palettes import brewer

months = ['JAN', 'FEB', 'MAR']
data = {"month" : months,
        "cat1"  : [1, 4, 12],
        "cat2"  : [2, 5, 3],
        "cat3"  : [5, 6, 1],
        "cat4"  : [8, 2, 1],
        "cat5"  : [1, 1, 3]}
categories = list(data.keys())
categories.remove('month')
colors = brewer['YlGnBu'][len(categories)]

p = figure(x_range=months, plot_height=250, title="Categories by month",
           toolbar_location=None)
v = p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)

legend = Legend(items=[(x, [v[i]]) for i, x in enumerate(categories)], location=(0, -30))

p.add_layout(legend, 'right')

show(p)
© www.soinside.com 2019 - 2024. All rights reserved.