如何更改Python中数学形式的$$中的字体

a15*_*767 4 python fonts matplotlib

当我尝试使用 matplotlib 绘制图形时,我用文本和“数学文本”编写了 x 轴标签。因为我要在标签上写化学式,所以写成“$CO_2$浓度”。问题是我希望字体应该是 times new roman,但我无法以某种方式更改美元符号中的字体。有人可以帮我解决吗?非常感谢!

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()
Run Code Online (Sandbox Code Playgroud)

这是图片链接,你可能看到图片后发现Times new roman中没有“CO2”。 https://flic.kr/p/2dmh8pj

Imp*_*est 5

我认为将任何数学文本更改为任意字体并不容易。但是,如果"CO_2"仅包含常规符号,您可以\mathdefault{}使数学文本使用常规字体中的符号。

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

类似的东西r"$\mathdefault{\sum_\alpha^\beta\frac{i}{9}}$仍然会以通常的默认数学字体集呈现(除了 the "i"和 the 9,它们当然存在于 Times New Roman 中)。

在此输入图像描述

对于一般情况,您还可以将完整的数学字体集更改为任何可用的, cm, stix, stixsans, dejavuserifdejavusans最接近“Times New Roman”的是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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

一般推荐阅读MathText 教程