python-2.7 - Matplotlib 和 latex

标签 python-2.7 matplotlib fonts xelatex

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

相关文章:

html - 使用 swift 更改 UIWebView 中文本的字体和字体颜色

Python - "in"语句搜索对象列表缓慢

windows - 当 Gtk 和 win32ui 模块都导入时,Python.exe 在关闭 Gtk.main() 后继续运行

python - 在 Python 的默认字典中访问最后输入的键的最佳方法是什么?

python - 如何在相同标签下绘制多列条形图

html - 如何将 <font size ="10"> 转换为 px?

python - 制作一个空列表并附加字典的所有子键

python - 如何拆分包含电压随时间变化的数据帧,以便它可以单独存储每个波形/位的值

python - Pyplot 在缩放时保持文本大小

javascript - 有没有一种优雅的方式来处理支持使用多种字体和一个词