Matplotllib和Xelatex [英] Matplotllib and Xelatex

查看:54
本文介绍了Matplotllib和Xelatex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我试图找到问题的答案,但无法提出对我有用的东西.我的问题是:如何使用Xelatex在Matplotlib中编译文本?

我知道有此页面:

I tried to find the answer for my question for some time now but could not come up with something that works for me. My question is: How can you use Xelatex to compile text in Matplotlib?

I know that there is this page: http://matplotlib.org/users/pgf.html

However, I could not come up with something that would work. What I got up to now:

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')

Running this code produces the following warning: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pgf.py:51: UserWarning: error getting fonts from fc-list warnings.warn('error getting fonts from fc-list', UserWarning)

An output file is created but I don't the font is wrong (not Linux Libertine), even though I have the font installed and am able to use it with XeLaTex (I am able to write a pdf file using xelatex that is set in the Linux Libertine font).

Any help would be really appreciated....

解决方案

There are a few problems with your code:

  • You need to give latex the control over the fonts by using the option: 'pgf.rcfonts': False
  • You should also use unicode for xelatex: 'text.latex.unicode': True.
  • 'pgf.preamble' expects a python lists of single latex commands.
  • if you set the font to 'Linux Libertine O' you probably want serif fonts, so 'font.family': 'serif'
  • beware of escape sequences in the preamble, you should make it raw strings
  • add a unicode tag at the beginning of the file and be sure the encoding is utf-8

Using this, your code becomes:

# -*- 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:

这篇关于Matplotllib和Xelatex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆