在bokeh图中创建两条线图例

2022-04-07 00:00:00 python bokeh

问题描述

我正在尝试创建一个Bokeh图表,上面有很多单独的线,准确地说是14(不是我的主意,有人告诉我这样做)。问题是,请求的格式使图例沿着图表底部水平显示,并且图例太长而不适合,所以我需要它是两行,而我似乎找不到任何关于如何做到这一点的指示。希望以前有人曾解决过这个问题。

单行图例的当前代码。

#graph data to chart
r0  = p1.line(data['Time'], data['Signal 1'], line_color="MediumBlue")
r1  = p1.line(data['Time'], data['Signal 2'], line_color="MidnightBlue")
r2  = p1.line(data['Time'], data['Signal 3'], line_color="red", y_range_name="Temp")
r3  = p1.line(data['Time'], data['Signal 4']*10, line_color="gray", y_range_name="Temp")
r4  = p1.line(data['Time'], data['Signal 5']*3.281, line_color="gold")
r5  = p1.line(data['Time'], data['Signal 6'], line_color="brown", y_range_name="Temp")
r6  = p1.line(data['Time'], data['Signal 7'], line_color="tomato", y_range_name="Temp")
r7  = p1.line(data['Time'], data['Signal 8'], line_color="blue", line_dash="4 4", y_range_name="Temp")
r8  = p1.line(data['Time'], data['Signal 9'], line_color="cyan", y_range_name="Temp")
r9  = p1.line(data['Time'], data['Signal 10']*57.3, line_color="plum", y_range_name="Temp")
r10 = p1.line(data['Time'], data['Signal 11']*1.94, line_color="green", y_range_name="Temp")

#create html file
output_file("Engine_Disp_Test.html", title="Engine Disp Test")

#Configure Legend
legend=Legend(items=[
                     ("Signal 1" , [r0]),
                 ("Signal 2" , [r1]),
                 ("Signal 3" , [r2]),
                 ("Signal 4" , [r3]),
                 ("Signal 5", [r4]),
                 ("Signal 6", [r5]),
                 ("Signal 7", [r6]),
                 ("Signal 8", [r7]),
                 ("Signal 9", [r8]),
                 ("Signal 10", [r9]),
                 ("Signal 11", [r10])
                 ], location=(70,-10), orientation="horizontal")

解决方案

从bokeh0.12.4开始,没有自动将图例拆分成多行(或多列)的功能。但您可以通过添加两个图例来解决此问题。请注意,我调整了位置并添加了min_border_bottom值,因为底部的图例似乎在其他方面被切断了。

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

p = figure(min_border_bottom=130)

r1 = p.line(x=[0, 1], y=1, line_width=2, color="red")
r2 = p.line(x=[0, 1], y=2, line_width=2, color="blue")
r3 = p.line(x=[0, 1], y=3, line_width=2, color="green")
r4 = p.line(x=[0, 1], y=4, line_width=2, color="orange")

legend1 = Legend([items=[("r1" , [r1]), ("r2", [r2])],
                 location=(70,20), orientation="horizontal")

legend2 = Legend(items=[("r3" , [r3]), ("r4", [r4])],
                 location=(70,10), orientation="horizontal")

p.add_layout(legend1, 'below')
p.add_layout(legend2, 'below')

output_file("foo.html")

show(p)

相关文章