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

时间:2018-11-08 19:45:06

标签: python legend bokeh

我在Bokeh中有一个堆叠的vbar图表,其简化版可以复制为:

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,它解释了如何在绘图区域之外添加图例,但在示例中,给定的每个字形都分配给一个变量,然后将其标记并添加到{{1} }对象。我知道该怎么做,但是我相信Legend方法会在一个调用中创建多个字形,因此我不知道如何标记这些字形并将它们添加到单独的vbar_stack对象中以放置在外部图表区域?

或者,有没有更简单的方法在调用Legend时使用legend参数,然后将图例定位在图表区域之外?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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 :(得分: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)
相关问题