在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’。

在latex中,必须在序言中添加以下行,以呈现“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中做到这一点。任何帮助都是非常感谢的。
发布于 2018-12-17 10:00:06
Matplotlib使用它自己的TeX手工(纯Python)实现来完成所有的数学文本操作,因此您绝对不能假设标准LaTeX中的工作内容将与Matplotlib一起工作。话虽如此,你就是这样做的:
calligra字体以便Matplotlib能够看到它,然后重新构建字体缓存。- Lots of other threads deal with how to do this, I'm not going to go into detail, but here's some reference:
- Use a [font](https://stackoverflow.com/questions/7726852/how-to-use-a-random-otf-or-ttf-font-in-matplotlib) installed in a [random](https://matplotlib.org/examples/api/font_file.html) spot on your filesystem.
- How to [install](https://scentellegher.github.io/visualization/2018/05/02/custom-fonts-matplotlib.html) a new font into the Matplotlib managed font cache.
- List all [fonts](https://stackoverflow.com/q/8753835/425458) currently known to your install of Matplotlib.
- Here's a function I wrote a while ago that reliably does that:导入matplotlib def setMathtextFont(fontName='Helvetica',texFontFamilies=None):texFontFamilies = 'it‘、'rm’、'tt‘、'bf’、'cal‘、'sf’如果texFontFamilies不是其他的texFontFamilies texFontFamilies‘定制’})用于texFontFamily in texFontFamilies: matplotlib.rcParams.update({(‘mathtext.%’s‘’% texFontFamily):fontName})
对您来说,使用该函数的一个好方法是将\mathcal使用的字体替换为calligra:
setMathtextFont(“书法”、“卡尔”)
r'$\mathcal{foo}$',以及\math<whatever>宏的内容应该以所需的字体显示。- Here's how you'd change your label-making code:plt.ylabel(r'$\mathcal{r}$',fontsize=50)
这样就行了。
https://stackoverflow.com/questions/53812102
复制相似问题