python - matplotlib 中的乳胶字体 - Script-r
问题描述
在 matplotlib 中,可以轻松地使用 Latex 脚本来标记轴,或编写图例或任何其他文本。但是有没有办法在 matplotlib 中使用新字体,例如“script-r”?在以下代码中,我使用乳胶字体标记轴。
import numpy as np
import matplotlib.pyplot as plt
tmax=10
h=0.01
number_of_realizations=6
for n in range(number_of_realizations):
xpos1=0
xvel1=0
xlist=[]
tlist=[]
t=0
while t<tmax:
xlist.append(xpos1)
tlist.append(t)
xvel1=np.random.normal(loc=0.0, scale=1.0, size=None)
xpos2=xpos1+(h**0.5)*xvel1 # update position at time t
xpos1=xpos2
t=t+h
plt.plot(tlist, xlist)
plt.xlabel(r'$ t$', fontsize=50)
plt.ylabel(r'$r$', fontsize=50)
plt.title('Brownian motion', fontsize=20)
plt.show()
它产生下图
在乳胶中,必须在序言中添加以下行来呈现“script-r”
\DeclareFontFamily{T1}{calligra}{}
\DeclareFontShape{T1}{calligra}{m}{n}{<->s*[2.2]callig15}{}
\DeclareRobustCommand{\sr}{%
\mspace{-2mu}%
\text{\usefont{T1}{calligra}{m}{n}r\/}%
\mspace{2mu}%
}
我不明白如何在 matplotlib 中执行此操作。任何帮助表示赞赏。
解决方案
Matplotlib 使用它自己的 TeX 手动(纯 Python)实现来完成所有数学文本的工作,所以你绝对不能假设在标准 LaTeX 中工作的东西可以与 Matplotlib 一起工作。话虽如此,这就是你的做法:
安装
calligra
字体以便 Matplotlib 可以看到它,然后重建字体缓存。- 很多其他线程处理如何做到这一点,我不打算详细介绍,但这里有一些参考:
- 使用安装在文件系统上随机位置的字体。
- 如何将新字体安装到 Matplotlib 托管字体缓存中。
- 列出您安装的 Matplotlib 当前已知的所有字体。
- 很多其他线程处理如何做到这一点,我不打算详细介绍,但这里有一些参考:
用您选择的字体替换 Matplotlib 的 TeX 字体系列之一。
这是我不久前编写的一个函数,它可靠地做到了这一点:
import matplotlib def setMathtextFont(fontName='Helvetica', texFontFamilies=None): texFontFamilies = ['it','rm','tt','bf','cal','sf'] if texFontFamilies is None else texFontFamilies matplotlib.rcParams.update({'mathtext.fontset': 'custom'}) for texFontFamily in texFontFamilies: matplotlib.rcParams.update({('mathtext.%s' % texFontFamily): fontName})
对您来说,使用该功能的一个好方法是将使用的字体替换
\mathcal
为calligra
:setMathtextFont('calligra', ['cal'])
例如,标记您的图,宏
r'$\mathcal{foo}$'
的内容\math<whatever>
应该以所需的字体显示。以下是更改标签制作代码的方法:
plt.ylabel(r'$\mathcal{r}$', fontsize=50)
那应该这样做。
推荐阅读
- django - Django - MigrationSchemaMissing 错误窗口
- python - 如何用另一个变量替换一个变量。ruamel.yaml
- python - 返回背包最大值的问题
- java - 在这个特定问题中应用继承的 Java 方法是什么?
- reactjs - ReactJS/nextjs 无效的钩子调用
- java - HikariPC 连接池不在客户端之间共享连接池?
- python - Python 3.9.2 中的 reverse_shell.py 卡住了
- java - Android线程异常和recyclerview不更新信息
- oauth - Google Calendar API - 权限不足
- arrays - 从 void Array 中提取数据未正确发生