Matplotlib: how to exact align the title to the y label?

Viewed 1248

In matplotlib I can easily align the title to the left with this command:

ax.set_title(f"Title", ha='left', x=-0)

and I get:

Title aligned to the left

But sometimes I want to align the title to where the left label begins, to get something like:

Title aligned to the left label

I usually do it by trial and error. At the end I get an arbitrary x offset like:

ax.set_title(f"Title", ha='left', x=-.12)

How would I automatically calculate this -.12 offset?

1 Answers

Using transformations (see Transformation tutorial), you can find the position of the left side of the label bounding box and transform that into axes coordinates to pass to set_title():

fig, ax = plt.subplots()
fig.canvas.draw()
bbox = ax.get_yticklabels()[-1].get_window_extent()
x,_ = ax.transAxes.inverted().transform([bbox.x0, bbox.y0])
ax.set_title('A title aligned with the y-axis labels', ha='left', x=x)

enter image description here

Related