Is there a way to position text in a figure by the fraction of the axis? I want the text in the same position for all my plots regardless of their differing ranges in x and y. This functionality is in ax.annotate() but I need to put in the extra 'xy' argument which makes my code harder to read.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10))
ax.annotate('Correct Position', xy=(0, 0), xytext=(0.4, 0.7), textcoords='axes fraction')
ax.text(0.4, 0.7, 'Incorrect Position')
plt.show()
Use xytext=(x,y) to set the coordinates of the text. You can provide these coordinates in absolute values (in data, axes, or figure coordinates), or in relative position using textcoords="offset points" for example.
BboxTransformTo is a transformation that linearly transforms points from the unit bounding box to a given Bbox. In your case, the transform itself is based upon a TransformedBBox which again has a Bbox upon which it is based and a transform - for this nested instance an Affine2D transform.
axes. text() is used to add text at an arbitrary location of the Axes. For this we need to specify the location of the text and of course what the text is.
You can use the transform
keyword:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10))
ax.text(0.4, 0.7, 'Correct Position', transform=ax.transAxes)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With