How to share labels and annotations between several separate plots?

EDIT: Solved. I’m an idiot. After posting this I found this answer
Specifically

Don’t create models at the top level of a cell. Instead, wrap them all in a function and call that function (similar to how bokeh serve does it internally)

So I wrapped all of the annotation variable definitions, the list, and the iteration in a function and just call that for each plot and then it works fine. Maybe another poor soul will find this and get back on track in the future.


What are you trying to do?

I’d like to keep my notebook DRY by reusing the same set of annotations and labels across many different individual plots.

What have you tried that did NOT work as expected?

I tried defining a set of annotations and variables in a list and then iterating through them to add them to a given plot like this

layouts = [span1, span2, box1, box2, label1, label2]                              

and then just adding one simple iteration to add it to each figure like this

for l in layouts:
    p.add_layout(l)

That way if I want to add or remove these annotations in the future I can do that in one place instead of many.
To my surprise, it works perfectly for the first one, but then when I try to add that same code to the next figure, I get the dreaded

RuntimeError: Models must be owned by only a single document, BoxAnnotation(id='1006', ...) is already in a doc

The viewing/saving pattern I’ve established between each successive figure is

show(p)
save(p, filename='p.html')
reset_output()
output_notebook()

I assumed that hanging those annotations on different figures would generate different IDs, but I see I’m wrong. After I generate each figure I immediately save it as .HTML to use elsewhere, so I think I just need a way to reset everything for the next cell so I can make my next figure and reuse the same set of annotations, but I haven’t found a clear way to do that. reset_output() doesn’t do it, and I thought something under curdoc() like a “clear” or “destroy” function would work, but nothing is obvious. Maybe my entire logic or structure is wrong, but since I’m working in entirely static documents I just need a way to say “save this and let me move on to the next figure starting from scratch so I can reuse those annotations.”

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.