gpt4 book ai didi

python-2.7 - Matplotlib 和 latex

转载 作者:行者123 更新时间:2023-12-04 18:02:33 26 4
gpt4 key购买 nike

一段时间以来,我一直试图找到我的问题的答案,但无法找到适合我的答案。我的问题是:如何使用 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')

结果:

result

关于python-2.7 - Matplotlib 和 latex ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com