Skillversitas

Customising Legends

Legends in Bokeh are layout models, so you can position, style, and compose them freely: multiple legends on one plot, custom titles and borders, per-item glyph overrides, and interactive legend clicks that toggle series visibility.

Positioning and Layout

from bokeh.plotting import figure

p = figure()
p.circle([1, 2], [1, 2], legend_label="A")
p.square([2, 3], [3, 4], legend_label="B")

p.legend.location = "outside_above_right"
p.legend.orientation = "horizontal"
p.legend.offset = (10, -20)

Styling the Legend Box

p.legend.title = "Datasets"
p.legend.title_text_font_size = "13pt"
p.legend.title_text_align = "left"
p.legend.background_fill_color = "#fff8e1"
p.legend.background_fill_alpha = 0.9
p.legend.border_line_color = "#d4af37"
p.legend.border_line_width = 1
p.legend.label_text_color = "#333"
p.legend.label_text_font_size = "11pt"

Multiple Legends

from bokeh.models import Legend

p = figure()
p.circle([1, 2], [1, 2], legend_label="A")
p.square([2, 3], [3, 4], legend_label="B")
p.triangle([3, 4], [2, 1], legend_label="C")

# first legend shows A and B; second shows C
p.legend = Legend(items=[p.renderers[0], p.renderers[1]], location="top_left")
p.add_layout(Legend(items=[p.renderers[2]], location="top_right"))

Interactive Legends (Click to Toggle)

p.legend.click_policy = "hide"     # click a legend item to hide its series
# other policies: "mute", "select", "destroy", "none"

Overriding Item Glyphs

from bokeh.models import LegendItem

p = figure()
r = p.circle([1, 2], [1, 2])
item = LegendItem(label="circle series",
                  renderers=[r],
                  glyph=r.glyph)   # use the glyph as the legend marker
p.legend.items.append(item)

Tips

  • Outside placement (outside_above_right) keeps the plot area uncluttered.
  • Use click_policy="hide" for dashboards where users filter by series.
  • Match legend colors to series colors by default - Bokeh does this automatically from glyph colors.

Summary

Customize legends by positioning and offsetting them, styling the box (background, border, title, fonts), composing multiple legends with add_layout(Legend(...)), enabling click-to-hide with click_policy, and overriding per-item glyphs. The legend is just a layout model, so every normal layout/style property applies.