Will.Evo Will.Evo - 4 months ago 14x
Python Question

Force LaTeX font to match default matplotlib font

I have seen this issue pop up here and there but have yet to find a suitable answer.

When making a plot in matplotlib, the only way to insert symbols and math functions (like fractions, exponents, etc...) is to use TeX formatting. However, by default TeX formatting uses a different font AND italicizes the text. So for example, if I wanted an axis label to say the following:


I have to do the following:


This produces a very ugly label that uses 2 different fonts and has bits and pieces italicized.

How do I permanently change the font of TeX (Not the other way around) so that it matches the default font used by matplotlib?

I have seen other solutions that tell the user to manually make all text the same in a plot by using \mathrm{} for example but this is ridiculously tedious. I have also seen solutions which change the default font of matplotlib to match TeX which seem utterly backwards to me.


It turns out the solution was rather simple and a colleague of mine had the solution.

If I were to use this line of code to create a title:

fig.suptitle(r'$H_2$ Emission from GJ832')

The result would be "H2 Emission from GJ832" which is an illustration of the problem I was having. However, it turns out anything inside of the $$ is converted to math type and thus the italics assigned.

If we change that line of code to the following:

fig.suptitle(r'H$_2$ Emission from GJ832')

Then the result is "H2 Emission from GJ832" without the italics. So this is an example of where we can constrain the math type to include only the math parts of the text, namely creating the subscript of 2.

However, if I were to change the code to the following:

fig.suptitle(r'H$_{two}$ Emission from GJ832')

the result would be "Htwo Emission from GJ832" which introduces the italics again. In this case, and for any case where you must have text (or are creating unit symbols) inside the dollar signs, you can easily remove the italics the following way:

fig.suptitle(r'H$_{\rm two}$ Emission from GJ832')

or in the case of creating a symbol:

ax2.set_xlabel(r'Wavelength ($\rm \AA$)')

The former results in "Htwo Emission from GJ832"

and the latter in "Wavelength (A)" where A is the Angstrom symbol.

Both of these produce the desired result with nothing italicized by calling \rm before the text or symbol in the dollar signs. The result is nothing italicized INCLUDING the Angstrom symbol created by \AA.

While this doesn't change the default of the TeX formatting, it IS a simple solution to the problem and doesn't require any new packages. Thank you Roland Smith for the suggestions anyway. I hope this helps others who have been struggling with the same issue.