3
votes

How can I get the font to be Times New Roman when using maths typing in matplotlib. The default font is italic, and I'm trying to make it match the other axes titles.

I'm trying to use \mathrm{}:

plt.xlabel(r"$\frac{\mathrm{1}}{{\mathrm{Distance}}^2 \ (\mathrm{m}^2)}$")

as suggested on a matplotlib website (https://matplotlib.org/users/mathtext.html) but it still appears as a sans-serif font. Is there a way I can make this into Times new Roman? Thanks!

2
There are some things mixed here. Are you talking about the font itself (e.g. Arial, Helvetica, Times New Roman) or the font style (e.g. normal, italic, bold)? - ImportanceOfBeingErnest

2 Answers

6
votes

Interpreting the question you are looking for serif font in both the text on the axes, as well as any MathText using on the plot.

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"

plt.xlabel(r"$\frac{\mathrm{1}}{{\mathrm{Distance}}^2 \ (\mathrm{m}^2)}$")
plt.ylabel("Some normal text")
plt.tight_layout()
plt.show()

enter image description here

0
votes

Another use case is to want a serif font in math mode, but only for a specific character. A solution is to set the fontset to custom, then set a serif font for only the mathcal (calligraphic) set of characters. Here, I'm also setting the font style to italic:

import matplotlib.pyplot as plt

plt.rcParams['mathtext.fontset'] = 'custom'
plt.rcParams['mathtext.cal'] = 'stix:italic'  # changes only the mathcal subfamily

Then, get a single serif character (d, here), but keep the rest as the default math font with:

plt.ylabel(r'Label ($a^b = \mathcal{d}$)')