pythonmatplotliblatex

How to change the power of two to be same font as rest of axis


I wish to use the default Pdflatex font (which I understand to be computer modern) for all of the text in my plots, as this is the same as I am using in my report. In an effort to have my figures be consistent within and with my report, I am using the following code to setup my Matplotlib before plotting:

import matplotlib.pyplot as plt

import matplotlib as mpl
mpl.rcParams['font.family'] = "serif"
mpl.rcParams['font.serif'] = "cmr10"
mpl.rcParams['axes.formatter.use_mathtext'] = True

Then I create the figure using the following:

fig, ax = plt.subplots()

ax.set_title('Results',fontsize=18)
ax.set_ylabel(r'Heat Flux (W/cm$^2$)',fontsize=18)
ax.set_xlabel('Wall Superheat (K)',fontsize=18)
ax.legend()

The problem is: I cannot get the power of two to be the same font as the rest of the axis title. Example of different font.

It is a small problem, but the '2' is not the same font as the rest of the label. Compare the two of the label with that of the 2 found in the axis ticks to see the difference.

The same problem exists when I try subscripts.

Kindly assist.


Solution

  • Using the \mathregular line worked.

    Thanks to import-random for directing me to an answer containing this expression.

    Example shown:

    import matplotlib.pyplot as plt
    
    import matplotlib as mpl
    mpl.rcParams['font.family'] = "serif"
    mpl.rcParams['font.serif'] = "cmr10"
    mpl.rcParams['axes.formatter.use_mathtext'] = True
    
    fig, ax = plt.subplots()
    
    ax.set_title('Results',fontsize=18)
    ax.set_ylabel('Heat Flux ($\mathregular{W/cm^{2}}$)',fontsize=18)
    ax.set_xlabel('Wall Superheat (K)',fontsize=18)
    

    This generates the '2' in the correct font.

    enter image description here