Can I get the as-rendered width of the legend box in pixels?

I am using the hack here to relocate my Legend outside the plot area. However, this “squashes” the plot area horizontally, which I don’t want. I need to increase the width of the figure:

the_figure.width += legend_width

But how to get legend_width? At the moment I’m doing the following horrible kludge to sum up the pixel widths of all the graphic elements that make up the Legend. This is especially irksome for the text labels, which look they are being rendered in a variable-width font, which looks OK so I don’t mind, but:

leg = the_figure.legend[0]
all_label_len = [ len(x.label['value']) for x in leg.items ]
max_label_len = max ( all_label_len )
label_font_size = leg.label_text_font_size
# It's a string like '13px` so need to int-ify it:
label_font_size = int(label_font_size[:-2])
max_label_width = max_label_len * label_font_size
# Here it comes ... ugh
legend_width = 2 * ( leg.border_line_width + leg.margin + leg.padding) + leg.glyph_width + max_label_width

This is clumsy and fragile, so surely there must be a better way! I’ve scoured the docs and there doesn’t appear to be any attribute of a Legend object that corresponds to what I want. Please can someone help?

1 Like

Like most things in Bokeh, all of the actual work is done on the BokehJS side, in the browser. Legend models have a couple of dozen properties for various sizes, standoffs, padding, spacing, font sizes, visibility, and items, and all of these contribute to the final overall size, which is not computed until render time in the browser. Considering the option for dynamic item grouping on the BokehJS side, it’s not even possible to know the number of legend items up front in general. So, TLDR; I am afraid this information does not exist in the Python API.

The very best we could even potentially do here is to add readonly property for these dimensions, but that would only be useful at all in Bokeh Server applications, or in JS callbacks. If that would still be interesting even with those limitations, please feel free to open a GitHub Issue to request it be considered for future development.

1 Like

Thank you for the speedy and helpful reply, Bryan (helpful for saving me from wasting time trying to wheedle this information out of the Python interface). Oh, and Merry Christmas!

1 Like

I was also wondering if this was possible, see last sentence in this post:
Is it possible to set manually the width of the plotting area, letting the legend expand right at will?