43

我想用乳胶计算机现代字体为我的图创建标签。然而,说服 matplotlib 使用 Latex 字体的唯一方法是插入如下内容:

title(r'$\mathrm{test}$')

这当然很荒谬,我告诉 Latex 启动数学模式,然后暂时退出数学模式以写入实际字符串。如何确保所有标签都以乳胶呈现,而不仅仅是公式?我如何确保这将是默认行为?

一个最小的工作示例如下:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# use latex for font rendering
mpl.rcParams['text.usetex'] = True


x = np.linspace(-50,50,100)
y = np.sin(x)**2/x
plt.plot(x,y)

plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$')
plt.ylabel(r'Not a latex font')
plt.show()

这给出了以下结果:

显示不正确渲染乳胶字体类型的绘图

这里的 x 轴是我希望标签出现的方式。如何确保所有标签都像这样显示而无需进入数学模式并再次返回?

4

3 回答 3

49

默认的 Latex 字体称为Computer Modern

from matplotlib import rc
import matplotlib.pylab as plt

rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)

x = plt.linspace(0,5)
plt.plot(x,plt.sin(x))
plt.ylabel(r"This is $\sin(x)$", size=20)
plt.show()

在此处输入图像描述

于 2013-07-31T09:59:45.250 回答
11

我在 Mac OSX 上使用 matplotlib 1.3.1,matplotlibrc为我添加以下行

text.usetex : True
font.family : serif 
font.serif  : cm

使用=导致UserWarning: Illegal line

于 2014-04-07T01:22:31.350 回答
9

默认情况下,可以通过更改matplotlibrc文件中的几行来启用标记的答案:

text.usetex = True
font.family = serif 
font.serif = cm
于 2013-08-14T20:02:04.843 回答