Exemples de comment ajouter du texte sur une figure avec matplotlib de python:
Ajouter de texte avec pyplot.text()
Pour ajouter du texte sur une figure Matplotlib il existe la méthode matplotlib.pyplot.text qui accepte comme arguments de base (x,y,s) avec x l'abscisse, y l'ordonnée et s le texte (de type string). Exemple simple d'application (texte 'Hello World !' aux coordonnées (1,35)):

#!/usr/bin/env pythonimport numpy as npimport matplotlib.pyplot as pltx = np.arange(0,4,0.2)y = np.exp(x)plt.text(1,35,'Hello World !')plt.grid()plt.plot(x,y)plt.show()
Position relative du texte
Si vous ne souhaitez pas placer le texte en fonction des coordonnées (x,y) , car c'est difficile à automatiser, mais en relativement aux axes il est possible d'utiliser l'approche suivante (dans ce cas x et y vont de 0 à 1, dans l'exemple ci dessous x = 0.5 et y = 0.5 c'est à dire au milieu de la figure):

#!/usr/bin/env pythonimport numpy as npimport matplotlib.pyplot as pltf = plt.figure()ax = f.add_subplot(111)x = np.arange(0,4,0.2)y = np.exp(x)plt.text(0.5,0.5,'Hello World !',horizontalalignment='center',verticalalignment='center', transform = ax.transAxes)plt.grid()plt.plot(x,y)plt.savefig('TextTest02.png')plt.show()
Ajouter du texte avec LaTeX
Vous pouvez aussi mettre du texte formater par LaTeX:

#!/usr/bin/env pythonimport numpy as npimport matplotlib.pyplot as pltf = plt.figure()ax = f.add_subplot(111)x = np.arange(0,4,0.2)y = np.exp(x)plt.text(0.5,0.5,r'$y = e^{x}$',horizontalalignment='center',verticalalignment='center', transform = ax.transAxes)plt.grid()plt.plot(x,y)plt.savefig('TextTest03.png')plt.show()
Changer la mise en forme
On peut aussi facilement changer la taille, la couleur, etc

#!/usr/bin/env pythonimport numpy as npimport matplotlib.pyplot as pltf = plt.figure()ax = f.add_subplot(111)x = np.arange(0,4,0.2)y = np.exp(x)plt.text(0.5,0.5,'Hello World !',horizontalalignment='center',verticalalignment='center', transform = ax.transAxes, fontsize=14, color='r')plt.grid()plt.plot(x,y)plt.savefig('TextTest04.png')plt.show()
Références
| Liens | Site |
|---|---|
| Putting text in top left corner of matplotlib plot | stackoverflow |
| matplotlib write text in the margin | stack overflow |
| matplotlib.pyplot.figtext | matplotlib doc |
| matplotlib.pyplot.text | matplotlib doc |
