Is there a generic API for setting plot annotations?


If I have an app that allows the user to specify plot annotatiaons in a YAML format, which becomes a python nested dict, for example, here might be some user-provided annotations:

annot = {
    'title': {
        'text':  'perplexity',
        'font_size': '24px',
    'xaxis': {
        'axis_label':  'sgd steps',
        'font_size': '16px',

I wondered, what is the most ergonomic way of assigning these to a given figure?
In the annotations docs, I see some examples of setting various annotations directly as python properties or sub-properties. For example:

p.title.text = 'perplexity'
p.title.font_size = '24px'
p.xaxis.axis_label = 'sgd steps'
p.xaxis.font_size = '16px'

I would like to avoid writing the code like:

p.__dict__[key].__dict__[key2] = val

Wondering if there was a better way to do this generically. Thanks in advance for any help!



FYI this almost certainly won’t work. In order to support cross-runtime validation, serialization, and documentation, Bokeh properties are actually object descriptors on metaclasses. They need to be actually set as actual attributes in order to invoke the critical descriptor protocol codepaths. So you’d need to go through setattr for this.

You could potentially leverage themes in this case:

Themes actually allow you to specify values for any Bokeh property. But note that they are type-based, per Document. e.g. you can set a new default font size for all title objects, or tick label orientations on all axes. You could technically specify a default title text, but it will apply to all plots (so probably not useful unless you just have one plot).

Oh, there is also update on Models that you can apply to individual Bokeh objects (e.g. to set individual title for individual distinct plots):

It’s a very rarely used function, but it’s probably more along the lines of what you want, since you could pass in a dict of values as kwargs. It won’t process nested values, though. You’ll still need to get ahold of individual objects to update a batch of its properties.

1 Like

Hi Bryan,

Thanks again! The update function looks nice - That will be helpful and I can make it work. Themes might work too, although I am using multiplle plots per page.



1 Like