Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning text by axis fraction

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()
like image 998
Keith Avatar asked May 26 '15 16:05

Keith


People also ask

How do I offset text in Matplotlib?

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.

What is BBOX in Matplotlib?

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.

Which command is used to print a text at a specific location on the plot area?

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.


1 Answers

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()
like image 197
Julien Spronck Avatar answered Oct 14 '22 16:10

Julien Spronck