Search code examples
pythonmatplotlibfontslabelitalic

Matplotlib Italic in portion of axes labels - applied to default font but not specified font


I want all text in my plots to be Times New Roman, so I did the following:

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman" # change default font

and I only want the '(x)' and '(z)' portions of my labels to be italics, so I did:

plt.xlabel('Underutilization $\it{(x)}$', labelpad=15)
plt.ylabel('Productivity $\it{(z)}$', labelpad=15)

However, what I end up with upon plotting is 'Underutilization' in Times New Roman, but '(x)' in an italicized sans serif (the default of Python). Same with the ylabel.

How can I remedy this?


Solution

  • The text inside the $ signs is dictated by matplotlib’s mathtext (unless you are using LaTex), and is controlled by the rcParam mathtext.fontset which is outlined in the documentation by

    mathtext.fontset: ‘dejavusans’ (default)
      ‘dejavuserif’, ‘cm’ (Computer Modern), ‘stix’,
      ‘stixsans’ or ‘custom’

    Using LaTex for the text rendering offers more flexibility in font choice, and I believe would support Times New Roman. If you use LaTex then it should adjust the math font when you adjust font.family.