How to add some text on a matplotlib figure in python ?

Daidalos November 07, 2019


Examples of how to add some text on a matplotlib figure in python:

Add text using pyplot.text()

To add some text on a matplotlib figure, a solution is to use the function matplotlib.pyplot.text() that needs the position of the text (x,y) and the text itself. An example with the text 'Hello World !' at the coordinates (1,35):

#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,4,0.2)
y = np.exp(x)

plt.text(1,35,'Hello World !')

plt.grid()
plt.plot(x,y)

plt.show()

The above code returns:

How to add some text on a matplotlib figure in python ?)

Add some text using a relative position

To place the text using a relative position (for example in the middle of the figure (0.5,0.5)) a solution is to do:

#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

f = 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()

returns

Ajouter du texte sur une figure Matplotlib (Position du texte relativement aux axes)

Add some text using LaTeX

It also possible to use LaTeX

#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

f = 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()

How to add some text on a matplotlib figure in python ?

Change text style

The text style can also be changed:

#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

f = 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()

How to add some text on a matplotlib figure in python ?

References

Links 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

Licence


Activity


Google Ads