问题
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....
回答1:
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:
来源:https://stackoverflow.com/questions/32725483/matplotllib-and-xelatex