我最近(也就是昨天)发现matplotlib在绘图方面比Matlab好得多。不幸的是,我对python的了解几乎为零。
我想在图例和/或轴中使用\mathbb{}
(例如,表示期望值或方差),这似乎需要额外的STIX字体(例如,参见here和here)。然而,到目前为止,我还不能在我的代码中包含这些字体。
在下面的示例中,我想替换\mathrm{E} --> \mathbb{E}
和\mathrm{V} --> \mathbb{V}
。有没有一种简单的方法呢?
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({'font.size': 8, 'text.usetex': True})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{E}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{V}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()
发布于 2020-12-23 22:45:32
\mathbb
是由LaTeX包amsfonts
提供的,因此您必须加载此包才能正确编译该图。您可以使用text.latex.preamble
设置加载包,如下所示:
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({
'font.size': 8,
'text.usetex': True,
'text.latex.preamble': r'\usepackage{amsfonts}'
})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathbb{E}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathbb{V}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()
或者,要使用您在问题中提到的STIX字体,您可以使用matplotlib内置的TeX解析器,而不是使用LaTeX进行文本处理(test.usetex
可以是False
)。但是,在本例中,请注意\mathbb{}
在默认情况下会生成斜体文本,您需要将其与\mathrm{}
作为\mathrm{\mathbb{}}
组合以获得竖排文本(如您所链接的示例中所示)。你的代码的一个可能版本是:
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({'font.size': 8})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{\mathbb{E}}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{\mathbb{V}}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()
In this case, this is the result. (posted as a link to limit the height of this answer)
https://stackoverflow.com/questions/65426069
复制相似问题