2

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?

tdy
  • 36,675
  • 19
  • 86
  • 83
Tom
  • 377
  • 3
  • 13

2 Answers2

2

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.

seralouk
  • 30,938
  • 9
  • 118
  • 133
  • Thanks so much! Exactly what I was looking for. I hadn't seen this done before and had no idea it was possible and so straightforward. – Tom Feb 16 '23 at 23:48
0

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

tdy
  • 36,675
  • 19
  • 86
  • 83