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

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}$)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With