【问题标题】:Matplotllib and XelatexMatplotlib 和 Xelatex
【发布时间】:2015-09-22 19:41:51
【问题描述】:

一段时间以来,我一直试图找到问题的答案,但无法找到适合我的方法。我的问题是:如何使用 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:用户警告:从 fc-list 获取字体时出错 warnings.warn('从 fc-list 获取字体时出错', UserWarning)

创建了一个输出文件,但我没有错误的字体(不是 Linux Libertine),即使我已经安装了字体并且能够将它与 XeLaTex 一起使用(我能够使用 xelatex 编写一个 pdf 文件设置为 Linux Libertine 字体)。

任何帮助将不胜感激......

【问题讨论】:

    标签: python-2.7 matplotlib fonts xelatex


    【解决方案1】:

    您的代码存在一些问题:

    • 您需要通过以下选项让 Latex 控制字体: 'pgf.rcfonts': False
    • 您还应该为 xelatex 使用 unicode:'text.latex.unicode': True
    • 'pgf.preamble' 需要一个包含单个乳胶命令的 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')
    

    结果:

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多