'How to display a text with matplotlib

I would like to do this :

I have this python code :

import numpy as np
import pylab as plt

a = np.array([1,2,3,4,5,6,7,8,9,10])
b = np.array([7,8,6,3,2,1,5,8,4,15])
c = plt.plot(a,b,'.')
d = 5
plt.text(2,3, "d = "+d) #This line is the problem because i have not the value of d !
plt.show()

So actually I just want to display the value of d and also I want to display the value of d but relatively for instance at the bottom right but not with some coordinates. Is it possible to do this with Python ?



Solution 1:[1]

You can use the transform argument to place in relative coordinates from 0.0 to 1.0 for example

plt.text(0.5,
         0.67,
         "d = {}".format(d),
         transform=plt.gca().transAxes)

In this local system (0, 0) is the lower-left and (1, 1) is the upper-right of the plot. Here is a good reference for placing and rotating text at various locations on the plot.

Solution 2:[2]

text

You can use text to place a text in the figure. By default, the coordinates are data coordinates, but you can specify a transform to switch e.g. to axes coordinates.

plt.text(.96,.94,"d={}".format(d), bbox={'facecolor':'w','pad':5},
         ha="right", va="top", transform=plt.gca().transAxes )

annotate

You can use annotate to produce a text somewhere in the figure. The advantage compared to text is that you may (a) use an additional arrow to point to an object, and (b) that you may specify the coordinate system in terms of a simple string, instead of a transform.

plt.annotate("d={}".format(d), xy=(p, 15), xytext=(.96,.94), 
            xycoords="data", textcoords="axes fraction",
            bbox={'facecolor':'w','pad':5}, ha="right", va="top")

AnchoredText

You can use an AnchoredText from offsetbox:

from matplotlib.offsetbox import AnchoredText
a = AnchoredText("d={}".format(d), loc=1, pad=0.4, borderpad=0.5)
plt.gca().add_artist(a)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cory Kramer
Solution 2 ImportanceOfBeingErnest