Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position the legend outside the plot area with Bokeh

I am making a plot following the example found here

Unfortunately, I have 17 curves I need to display, and the legend overlaps them. I know I can create a legend object that can be displayed outside the plot area like here, but I have 17 curves so using a loop is much more convenient.

Do you know how to combine both methods?

like image 656
Despe1990 Avatar asked Oct 13 '17 13:10

Despe1990


2 Answers

I'd like to expand on joelostbloms answer. It is also possible to pull out the legend from an existing plot and add it somewhere else after the plot has been created.

from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers


# add a column with colors to the data
colors = dict(zip(flowers['species'].unique(), Category10[10]))
flowers["color"] = [colors[species] for species in flowers["species"]]

# make plot
p = figure(height=350, width=500)
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color="color")
p.add_layout(p.legend[0], 'right')

show(p)
like image 176
Sam De Meyer Avatar answered Sep 20 '22 08:09

Sam De Meyer


It is also possible to place legends outside the plot areas for auto-grouped, indirectly created legends. The trick is to create an empty legend and use add_layout to place it outside the plot area before using the glyph legend_group parameter:

from bokeh.models import CategoricalColorMapper, Legend
from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.sampledata.iris import flowers


color_mapper = CategoricalColorMapper(
    factors=[x for x in flowers['species'].unique()], palette=Category10[10])
p = figure(height=350, width=500)
p.add_layout(Legend(), 'right')
p.circle("petal_length", "petal_width", source=flowers, legend_group='species',
         color=dict(field='species', transform=color_mapper))
show(p)

enter image description here

like image 36
joelostblom Avatar answered Sep 18 '22 08:09

joelostblom