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

2024-09-27 21:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图用matplotlib绘制一个图形时,我用文本和“数学文本”编写了x轴标签。因为我要在标签上写一个化学式,写的是“$CO_2$concentration”。问题是,我希望字体应该是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()

这是图片链接,你可以看到图片,发现“二氧化碳”不是在新罗马时代。 https://flic.kr/p/2dmh8pj


Tags: importreadaspltxlsxexcelpdco
2条回答

我发现最好一次定义整个字体系列,而不是单独定义(假设您想要相同的字体)。试试这个

plt.rc('text', usetex=True )
plt.rc('font', family='Times New Roman', weight='normal', size=14)
plt.rcParams['mathtext.fontset'] = 'Times New Roman'
ax1.set_xlabel('$CO_2$ pressure')
ax1.set_ylabel('$CO_2$ concentration')

我不认为将任何mathtext更改为任意字体是不容易的。但是,如果"CO_2"只包含常规符号,则可以使用\mathdefault{}使mathtext使用常规字体中的符号。在

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

类似r"$\mathdefault{\sum_\alpha^\beta\frac{i}{9}}$的内容仍将在通常的默认数学字体集中呈现(除了"i"和{},这两个元素当然存在于Times New Roman中)。在

enter image description here

对于一般情况,您还可以将完整的数学字体集更改为cmstixstixsansdejavuserifdejavusans。最接近“新罗马时代”的是stix。在

^{pr2}$

enter image description here

一般建议阅读MathText tutorial。在

相关问题 更多 >

    热门问题