一段时间以来,我一直试图找到我的问题的答案,但无法找到适合我的答案。我的问题是:如何使用 Xelatex 编译 Matplotlib 中的文本?
我知道有这个页面: http://matplotlib.org/users/pgf.html
但是,我无法想出可行的方法。我到现在为止:
import matplotlib as mpl
mpl.use("pgf")
## TeX preamble
preamble = """
\usepackage{fontspec}
\setmainfont{Linux Libertine O}
"""
params = {"text.usetex": True,
'pgf.texsystem': 'xelatex',
'pgf.preamble': preamble}
mpl.rcParams.update(params)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.xlabel(r'\textsc{Something in small caps}', fontsize=20)
plt.ylabel(r'Normal text ...', fontsize=20)
plt.savefig('test.pdf')
运行此代码会产生以下警告: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pgf.py:51: UserWarning: 从 fc-list 获取字体时出错 warnings.warn('从 fc-list 获取字体时出错', UserWarning)
创建了一个输出文件,但我没有发现字体错误(不是 Linux Libertine),即使我安装了字体并且能够将其与 XeLaTex 一起使用(我能够使用 xelatex 编写一个 pdf 文件以 Linux Libertine 字体设置)。
任何帮助将不胜感激....
最佳答案
您的代码存在一些问题:
- 您需要使用以下选项让 Latex 控制字体:
'pgf.rcfonts': False
- 您还应该为 xelatex 使用 unicode:
'text.latex.unicode': True
。 - 'pgf.preamble' 需要单个 latex 命令的 python 列表。
- 如果您将字体设置为“Linux Libertine O”,您可能需要衬线字体,
所以
'font.family': 'serif'
- 注意序言中的转义序列,你应该将其设为原始字符串
- 在文件开头添加unicode标签,确保编码为utf-8
使用这个,你的代码变成:
# -*- coding:utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
## TeX preamble
preamble = [
r'\usepackage{fontspec}',
r'\setmainfont{Linux Libertine O}',
]
params = {
'font.family': 'serif',
'text.usetex': True,
'text.latex.unicode': True,
'pgf.rcfonts': False,
'pgf.texsystem': 'xelatex',
'pgf.preamble': preamble,
}
mpl.rcParams.update(params)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.xlabel(r'\textsc{Something in small caps}', fontsize=20)
plt.ylabel(r'Normal text ...', fontsize=20)
plt.savefig('test.pdf')
结果:
关于python-2.7 - Matplotlib 和 latex ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725483/