How to ensure constant bar width across figures despite variable legend and ticklabel sizes?

I’m creating a bunch of horizontal bar figures and I’d like that the bar width is same across all the figures. The problem is that each figure has a different legend (all positioned on top, above the plotting area), which require different amount of vertical space (one, two or three text heights). I don’t know how much space is required before rendering.

One solution might be to access the rendered legend and add the required margin space dynamically, but as far as I understand, I cannot get the info about the rendered layout using Python. Is that right?

Another would be to compute the required number of lines using the known text and font size, but that seems quite complicated.

Is there another option I am missing?

I ended up getting the height of the rendered legend using clientside_callback, and adjusting the top margin accordingly:

# Get legend height
dash.clientside_callback(
    """
    function(n_intervals) {
        const legendElement = document.querySelector('g.legend');
        if (legendElement) {
            const bbox = legendElement.getBBox();
            return bbox.height;
        }
        return "";
    }
    """,
    dash.Output("legend-measurer", "data"),
    dash.Input("the-graph", "figure"),
)


@dash.callback(
    dash.Output("the-graph", "figure", allow_duplicate=True),
    dash.Input("legend-measurer", "data"),
    dash.State("the-graph", "figure"),
    prevent_initial_call=True,
)
def update_legend_height(legend_height, figure):
     ...
   figure["layout"]["height"] = legend_height + bar_height * num_bars
   figure["layout"]["margin"]["t"] = legend_height
   return figure