Skip to main content
 首页 » 编程设计

python之如何在 matplotlib 中使用 latex 创建 'normal' 外观轴标签

2025年05月04日19mfrbuaa

我有以下代码来创建带有德语变音符号的轴标签:

plt.xlabel('Daten') 
plt.ylabel(r'$H\ddot{a}ufigkeit$') 

这基本上可以正常工作,并且可以正确打印变音符号,但是 x 和 y 标签的字体现在不同了,因为 x 标签是在数学模式下打印的。将第二行更改为

plt.ylabel(r'$\textrm{H\ddot{a}ufigkeit}$') 

据我所知应该可以工作(为了创建一个类似 rm 的字体而不是数学模式字体),但给出了一个 python 错误:

matplotlib.pyparsing.ParseFatalException: Expected end of math '$' 

我该如何解决这个问题,以便在两个轴上使用相同的字体,但可以使用变音符号?

请您参考如下方法:

非数学元音是\":

plt.ylabel(r'H\"{a}ufigkeit') 

如果你需要 \ddot 只需将 $ 放在它的周围:

plt.ylabel(r'H$\ddot{a}$ufigkeit') 

顺便说一句,\textrm 命令只能在文本模式下使用。数学模式等价物是 \mathrm:

plt.ylabel(r'$\mathrm{H\ddot{a}ufigkeit}$') 

更新

以上所有假设您已经告诉 matplotlib 使用 tex 渲染。为此,请在代码顶部添加以下内容:

import matplotlib.pyplot as plt 
plt.rc('text', usetex=True)