4

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.

user1551817
  • 6,693
  • 22
  • 72
  • 109

1 Answers1

7

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

David
  • 567
  • 4
  • 16
  • Thanks. I did that, but it hasn't changed anything. The font is still sans serif. I am using matplotlib version 2.2.2 – user1551817 Nov 29 '19 at 10:38
  • 1
    @user1551817 I've added a full example to my answer. I've run it with 2.2.2 and it works. Maybe the cause of the problem is elsewhere in your code. – David Nov 29 '19 at 10:55
  • 1
    Thanks. It seems like doing "$example$" instead of "example" is the difference. – user1551817 Nov 29 '19 at 10:58
  • 1
    @user1551817 you are right. I have completed my answer addressing math expressions – David Nov 29 '19 at 11:45