bokeh / bokeh

Interactive Data Visualization in the browser, from Python
https://bokeh.org
BSD 3-Clause "New" or "Revised" License
19.41k stars 4.19k forks source link

[FEATURE] Allow BoxAnnotations in Legends #12117

Open mosc9575 opened 2 years ago

mosc9575 commented 2 years ago

Problem description

Sometimes I use BoxAnnotations to add additional information to a plot and I would like to have the opportunity to toggle visibility using a legend in the same way it is possible for Glyphs.

This is a slightly adapted version of the box_annotation example.

from bokeh.models import BoxAnnotation, Legend, LegendItem
from bokeh.plotting import figure, show
from bokeh.sampledata.glucose import data

data = data.loc['2010-10-04':'2010-10-04']

p = figure(title="Glocose Readings, Oct 4th\n(Red = Outside Range)",
           x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,save")
p.background_fill_color = "#efefef"
p.xgrid.grid_line_color=None
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Value'

p.line(data.index, data.glucose, line_color='grey')
p.scatter(data.index, data.glucose, color='grey', size=1)

boxes = []
boxes.append(BoxAnnotation(top=80, fill_alpha=0.1, fill_color='red', line_color='red'))
boxes.append(BoxAnnotation(bottom=180, fill_alpha=0.1, fill_color='red', line_color='red'))
p.renderers.extend(boxes)
# p.add_layout(Legend(items=[LegendItem(label='Background', renderers=boxes)]))
show(p)

If I uncommet the line with the Legend I get the error message:

ValueError: failed to validate LegendItem(id='2918', ...).renderers: expected an element of List(Instance(GlyphRenderer)), got seq with invalid items [BoxAnnotation(id='2916', ...), BoxAnnotation(id='2917', ...)]

Feature description

This is possibly a dupliacte, I found this comment in #9955

Allow annotations to be added to legends (this has come up several times recently)

Additional information

I am using Bokeh 2.4.2 and don't know if this already is changed on the development branch.

mattpap commented 2 years ago

Hopefully PR #12083, or a follow-up to it, will allow this.