pythonmatplotlib

With matplotlib, how to align text with Axes position independant of tight_layout


I want to have two text annotations on a Figure, that are aligned with the x positions of the Axes in the FIgure (x0 and x1). I can set it to work correctly normally, but when I call fig.tight_layout the text stays where it was before the layout changes.

Is there a way to have the text positions determined dynamically to where the Axes ends up being?

I know calling fig.tight_layout before setting the text works, but I wonder how to make the text's position dependant of the axes positions all the time.

Here is a sample code:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax_bbox = ax.get_position()

fig.text(ax_bbox.x0, 0.01, "left text", ha="left")
fig.text(ax_bbox.x1, 0.01, "right text", ha="right")

fig.tight_layout()  # this makes the axes position to change

plt.show()

The figure without fig.tight_layout without tight layout

The figure with fig.tight_layout with tight layout


Solution

  • It would be by giving the x and y coordinates related to the ax coords, specifying it by giving its transform as an argument:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    fig.text(0, -0.06, "left text", ha="left", va="top",  transform=ax.transAxes)
    fig.text(1, -0.06, "right text", ha="right", va="top", transform=ax.transAxes)
    
    fig.tight_layout()
    
    plt.show()
    

    plot with text under xaxis