Search code examples
pythonmatplotlibfonts

How to change font in $$ which is in math form in python


When I tried to polt a figure with matplotlib, I wrote the x axis label with both text and "math text". Because I have to write a chemical formula in the label, it was written as '$CO_2$ concentration'. The question is that I hope the font should be times new roman, but I cannot change the font in the dollar sign somehow. Is there anyone who can help me fix it? Thank you very much!

import numpy as np 
import matplotlib.pyplot as plt
import pandas as pd

xf1 = pd.read_excel('1812_GPT.xlsx',sheetname= 'PVD_CO2CH4_600',usecols=[1])
deltapx1 = pd.read_excel('1812_GPT.xlsx',sheetname= 'PVD_CO2CH4_600',usecols=[3])
Px1 = pd.read_excel('1812_GPT.xlsx',sheetname= 'PVD_CO2CH4_600',usecols=[5])

ax1 = plt.subplot(111) 

l1, = ax1.plot(xf1,Px1,'s',markerfacecolor='black')

font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 14,
 }

ax1.set_xlabel(r'$CO_2$ pressure', font1)
ax1.set_ylabel(r'$CO_2$ concentration', font1)

plt.show()

This is the picture link, you may see the pic and find that "CO2" is not in Times new roman. https://flic.kr/p/2dmh8pj


Solution

  • I don't think it's easily possible to change any mathtext to an arbitrary font. However, in case of "CO_2" that consists only of regular symbols, you may use \mathdefault{} to make the mathtext use the symbols from the regular font.

    import matplotlib.pyplot as plt
    
    plt.rcParams["font.family"] = "serif"
    plt.rcParams["font.serif"] = ["Times New Roman"] + plt.rcParams["font.serif"]
    
    fig, ax = plt.subplots()
    
    ax.set_xlabel(r'$\mathdefault{CO_2}$ pressure')
    ax.set_ylabel(r'$\mathdefault{CO_2}$ concentration')
    
    plt.show()
    

    enter image description here

    Something like r"$\mathdefault{\sum_\alpha^\beta\frac{i}{9}}$ would still be rendered in the usual default math fontset (except the "i" and the 9, which are of course present in Times New Roman).

    enter image description here

    For the general case, you may also change the complete math fontset to any of the available, cm, stix, stixsans, dejavuserif, dejavusans. The closest to "Times New Roman" would be stix.

    import matplotlib.pyplot as plt
    
    rc = {"font.family" : "serif", 
          "mathtext.fontset" : "stix"}
    plt.rcParams.update(rc)
    plt.rcParams["font.serif"] = ["Times New Roman"] + plt.rcParams["font.serif"]
    
    
    fig, ax = plt.subplots()
    
    ax.set_xlabel(r'$CO_2$ pressure')
    ax.set_ylabel(r'$CO_2$ concentration')
    
    plt.show()
    

    enter image description here

    A general recommendation for reading would be the MathText tutorial.