散景位置图例在堆叠vbar的绘图区域之外 [英] Bokeh Position Legend outside plot area for stacked vbar

查看:71
本文介绍了散景位置图例在堆叠vbar的绘图区域之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a stacked vbar chart in Bokeh, a simplified version of which can be reproduced with:

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)

我想在图表中添加图例,但是我的真实图表在堆栈中有很多类别,因此图例会非常大,因此我希望它位于右侧的绘图区域之外.

I want to add a legend to the chart, but my real chart has a lot of categories in the stacks and therefore the legend would be very large, so I want it to be outside the plot area to the right.

此处有一个SO答案,其中解释了如何在绘图区域之外添加图例,但在给出的示例中,每个呈现的字形都分配给一个变量,然后对其进行标记并添加到 Legend 对象.我知道该怎么做,但是我相信 vbar_stack 方法可以在一个调用中创建多个字形,因此我不知道如何标记这些字形并将它们添加到单独的 Legend 对象是否要放置在图表区域之外?

There's a SO answer here which explains how to add a legend outside of the plot area, but in the example given each glyph rendered is assigned to a variable which is then labelled and added to a Legend object. I understand how to do that, but I believe the vbar_stack method creates mutliple glyphs in a single call, so I don't know how to label these and add them to a separate Legend object to place outside the chart area?

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

Alternatively, is there a simpler way to use the legend argument when calling vbar_stack and then locate the legend outside the chart area?

非常感谢任何帮助.

推荐答案

对于有兴趣的人,现在已经使用 vbar_stack 字形的简单索引对其进行了修复.解决方案如下:

For anyone interested, have now fixed this using simple indexing of the vbar_stack glyphs. Solution below:

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)

这篇关于散景位置图例在堆叠vbar的绘图区域之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆