如何在Bokeh中创建图例标题?

6

有没有办法给图例添加标题,例如左侧的当前图例,右侧带标题的图例。这个特定的图例放在绘图区域外面,所以我不知道是否可以用文本标志来伪造它。

legend images

2个回答

4

在最新版本的Bokeh (1.2)中,您可以按照以下方式向图例添加标题:

p.legend.title = 'Example Title'

完整的例子:
import numpy as np

from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, output_file

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"

p1 = figure(title="Legend Example", tools=TOOLS)

p1.circle(x,   y, legend="sin(x)")
p1.circle(x, 2*y, legend="2*sin(x)", color="orange")
p1.circle(x, 3*y, legend="3*sin(x)", color="green")

p1.legend.title = 'Example Title'

p2 = figure(title="Another Legend Example", tools=TOOLS)

p2.circle(x, y, legend="sin(x)")
p2.line(x, y, legend="sin(x)")

p2.line(x, 2*y, legend="2*sin(x)", line_dash=(4, 4), line_color="orange", line_width=2)

p2.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green")
p2.line(x, 3*y, legend="3*sin(x)", line_color="green")

output_file("legend.html", title="legend.py example")

show(gridplot([p1, p2], ncols=2, plot_width=400, plot_height=400)) 

这段代码来自官方文档


4

更新: 这种方法已不再必要。请参见被接受的答案。

我发现在Bokeh库中仍然没有实现一种添加图例标题的方法,但我实现的解决方案如下: 在添加任何其他图表之前添加一个非常小的白点。

示例代码:

import numpy as np
from bokeh.plotting import output_file, figure, show

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
legend_title = "Math Functions" #Legend Title 

output_file("legend_labels.html")

p = figure()

p.circle(0, 0, size=0.00000001, color= "#ffffff", legend=legend_title)

p.circle(x, y, legend="sin(x)")
p.line(x, y, legend="sin(x)")

p.line(x, 2*y, legend="2*sin(x)",
   line_dash=[4, 4], line_color="orange", line_width=2)

p.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green")
p.line(x, 3*y, legend="3*sin(x)", line_color="green")

p.legend.label_text_font = "times"
p.legend.label_text_font_style = "italic"
p.legend.label_text_color = "navy"

show(p)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接