# 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:

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:

### 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()

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

### 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()

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

### 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()

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