首页 > 解决方案 > 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'代替普通的'r'。脚本 r

在乳胶中,必须在序言中添加以下行来呈现“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 中执行此操作。任何帮助表示赞赏。

标签: pythonmatplotlibfontslatex

解决方案


Matplotlib 使用它自己的 TeX 手动(纯 Python)实现来完成所有数学文本的工作,所以你绝对不能假设在标准 LaTeX 中工作的东西可以与 Matplotlib 一起工作。话虽如此,这就是你的做法:

  1. 安装calligra字体以便 Matplotlib 可以看到它,然后重建字体缓存。

  2. 用您选择的字体替换 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})
      

      对您来说,使用该功能的一个好方法是将使用的字体替换\mathcalcalligra

      setMathtextFont('calligra', ['cal'])
      
  3. 例如,标记您的图,宏r'$\mathcal{foo}$'的内容\math<whatever>应该以所需的字体显示。

    • 以下是更改标签制作代码的方法:

      plt.ylabel(r'$\mathcal{r}$', fontsize=50)
      

那应该这样做。


推荐阅读