'Changing the font of ax.text in matplotlib

I am making a python plot using matplotlib.

At the start of the code, I use:

plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']

in order to change the font of the text in my plots.

I also use:

ax.text(0.5,0.5, r'$test_{1}$', horizontalalignment='center', verticalalignment='center', size=18)

But this text is not Times New Roman.

How do I make the ax.text Times New Roman?

Thanks.



Solution 1:[1]

1. Parameter fontdict

The Axes.text matplotlib documentation says:

If fontdict is None, the defaults are determined by your rc parameters.

So you have to include fontdict=None in ax.text(), in order to display its font as specified in rcParams.

ax.text(..., fontdict=None)

The fontdict parameter is available since matplotlib 2.0.0.

2. Math expressions

Besides, for math expressions like $a=b$, the docs say:

This default [font] can be changed using the mathtext.default rcParam. This is useful, for example, to use the same font as regular non-math text for math text, by setting it to regular.

So you also need to set the default font to 'regular':

rcParams['mathtext.default'] = 'regular'

This option is available at least since matplotlib 2.1.0

3. Example

Your code should now look something similar to:

import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
plt.rcParams['mathtext.default'] = 'regular'

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])

ax.text(0.5, 0.5, '$example$', horizontalalignment='center', 
        verticalalignment='center', size=18, fontdict=None)

plt.show()

enter image description here

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