MajorYel
MajorYel

Reputation: 389

Position of the legend in a Bokeh plot

Does anyone know how to carry the legend in bokeh outside of the graph? The only manipulation I could do was to choose a position among:

top_right, top_left, bottom_left or bottom_right

using:

legend()[0].orientation = "bottom_left"

and when I try different ones I get the error message:

ValueError: invalid value for orientation: 'outside'; allowed values are top_right, top_left, bottom_left or bottom_right

Upvotes: 26

Views: 37745

Answers (2)

Mehdi
Mehdi

Reputation: 1167

According to the Bokeh documentation and bigreddot, one way is to use the Legend command. I found another way.

If you use the legend_label argument in the plotting functions such as quad() or line(), the plot labels are appended to the p.legend. The location of the legend is defined by p.legend.location = "center" as a normal way.

To put the legend outside, you should use p.add_layout(p.legend[0], 'right').

Here is the above code in a different way.

import numpy as np

from bokeh.plotting import figure, output_file, show

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

output_file("legend_labels.html")

p = figure()

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

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

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

p.legend.location = "center"

########################################################
# This line puts the legend outside of the plot area

p.add_layout(p.legend[0], 'right')
########################################################

show(p)

Upvotes: 6

bigreddot
bigreddot

Reputation: 34568

As of Bokeh 0.12.4 it is possible to position legends outside the central plot area. Here is a short example from the user's guide:

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

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

output_file("legend_labels.html")

p = figure(toolbar_location="above")

r0 = p.circle(x, y)
r1 = p.line(x, y)

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

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

legend = Legend(items=[
    ("sin(x)",   [r0, r1]),
    ("2*sin(x)", [r2]),
    ("3*sin(x)", [r3, r4])
], location=(0, -30))

p.add_layout(legend, 'right')

show(p)

To adjust the position, change dx and dy in location=(dx, dy).

enter image description here

Upvotes: 26

Related Questions