初学Bokeh:添加&修改图例的样式 【11】跬步

发布时间 2023-10-18 17:44:49作者: ohfaint

初学Bokeh:添加&修改图例的样式 【11】跬步

如果在调用渲染器函数时包含了legend_label属性,Bokeh会自动将一个图例添加到绘图中。 例如:

p.circle(x, y3, legend_label="Objects")

从而为你绘制的图形添加一个带有“Objects”条目的图例。改变图例对象的属性可以对图例进行自定义。例如:

from bokeh.plotting import figure, show

# 数据准备
x = [1, 2, 3, 4, 5]
y1 = [4, 5, 5, 7, 2]
y2 = [2, 3, 4, 5, 6]

# 创建一个新的图形
p = figure(title="Legend example")

# 绘制多个线段与圆,添加图例
line = p.line(x, y1, legend_label="Temp.", line_color="blue", line_width=2)
circle = p.circle(
    x,
    y2,
    legend_label="Objects",
    fill_color="red",
    fill_alpha=0.5,
    line_color="blue",
    size=80,
)

# 在左上角显示图例 (图例的默认位置在图形的右上角)
p.legend.location = "top_left"

# 为图例增加一个标题
p.legend.title = "Obervations"

# 改变图例的字体形式
p.legend.label_text_font = "times"
p.legend.label_text_font_style = "italic"
p.legend.label_text_color = "navy"

# 改变图例的边线颜色和背景色
p.legend.border_line_width = 3  # 设置边线宽度
p.legend.border_line_color = "navy" # 设置边线颜色
p.legend.border_line_alpha = 0.8    # 设置边线透明度
p.legend.background_fill_color = "navy" # 设置背景色
p.legend.background_fill_alpha = 0.2    # 设置背景色的透明度

# 显示
show(p)

fig1