Customized Legend

Hello,

I have a vbar graph in which I’m using conditional colors for each bar. I was hoping I could put a legend on the graph that gives a description of what each color means.

Shortened code:

xAxis=[1, 2, 3, 4, 5]
precipchance=[40,50,60,30,40]
condColor=['red', 'green', 'blue', 'green', 'red']
p.vbar(x=xAxis, top=precipchance, color=condColor)

Produces:

I would like the legend to have a red square = “Thunderstorms”, green square = “Rain”, etc.

Is something like this possible?

@MABeatty If you use a ColumnDataSource for your data and add a field that describes each observation then you can use legend_group in the vbar glyph method. Below I used your data and added the label field.

from bokeh.io import output_notebook, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

ptest=figure()

source = ColumnDataSource(dict(
    x = [1, 2, 3, 4, 5],
    top = [40,50,60,30,40],
    color = ['red', 'green', 'blue', 'green', 'red'],
    label = ['Thunderstorms', 'Rain', 'Blue sky', 'Rain', 'Thunderstorms'],
))

ptest.vbar(
    x = 'x', top = 'top',
    color = 'color',
    legend_group = 'label',
    source = source
)
output_notebook()
show(ptest)

Have a look in the documentation for more details regarding legends.

2 Likes

That worked perfectly, thank you!

1 Like