How can I add text to the same position in multiple matplotlib plots with different axis scales?

Question:

I have ~20 plots with different axes, ranging from scales of 0-1 to 0-300. I want to use plt.text(x,y) to add text to the top left corner in my automated plotting function, but the changing axis size does not allow for this to be automated and completely consistent.

Here are two example plots:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

#Plot 2
plt.plot([2, 4, 6, 8])
plt.ylabel('some numbers')
plt.show()

I want to use something like plt.text(x, y, 'text', fontsize=8) in both plots, but without specifying the x and y for each plot by hand, instead just saying that the text should go in the top left. Is this possible?

Asked By: Trev

||

Answers:

Have you tried ax.text with transform=ax.transAxes?

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1, 2, 3, 4])
ax.set_ylabel('XXX')

ax.text(0.05, 0.95, 'text', transform=ax.transAxes, fontsize=8, va='top', ha='left')

plt.show()

Explanation:

The ax.text takes first the x and y coordinates of the text, then the transform argument which specifies the coordinate system to use, and the va and ha arguments which specify the vertical and horizontal alignment of the text.

Answered By: seralouk

Use ax.annotate with axes fraction coordinates:

fig, axs = plt.subplots(1, 2)

axs[0].plot([0, 0.8, 1, 0.5])
axs[1].plot([10, 300, 200])

for ax in axs:
    ax.annotate('text', (0.05, 0.9), xycoords='axes fraction')
    #                                ------------------------

Here (0.05, 0.9) refers to 5% and 90% of the axes lengths, regardless of the data:

figure output

Answered By: tdy