Help with finding legend bounding boxes's exact coordinates

Hello there, it’s my first time here.

So I’m trying to create a dataset of synthetically generated charts to train a neural net to find bounding boxes for different elements of a chart - legend box, chart title, axes labels, etc.

For the legend box, I have tried loc, but it only gives control over one corner of the bounding box. I want coordinates for both diagonal’s corners after they have been plotted onto the chart by Matplotlib.

I also tried using get_tightbbox from here but it is giving me the error AttributeError: 'Legend' object has no attribute 'get_tightbbox'. The code I used is below:

x_line = np.linspace(0, 10, 10)
y_line = np.random.uniform(size=(10,))

fig, ax = plt.subplots()
ax.plot(x_line, y_line)
leg = ax.legend(['line 1'])
p = leg.get_tightbbox(fig.canvas.get_renderer(),
                     call_axes_locator = True)

I would appreciate any help with the above code, or any ideas on how to find bboxes for my problem as described above. (legend box, chart title, axes labels, etc.)


I figured out how to do it.
Here’s what I did incase someone else might need it.

The Matplotlib artists documentation mentions that each artist has its own properties which can be listed by the handy function matplotlib.artist.getp({artist}).

So, I simply did leg.get_window_extent() from the above code to get the bbox coordinates.
I was able to get the bboxes for all the other elements in a similar manner.