# XeLaTeX/LuaLaTeX 設置
> 原文:[Typesetting With XeLaTeX/LuaLaTeX](http://matplotlib.org/users/pgf.html)
> 譯者:[飛龍](https://github.com/)
> 協議:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
使用 pgf 后端,matplotlib 可以將圖形導出為可以使用 pdflatex,xelatex 或 lualatex 處理的 pgf 繪圖命令。 XeLaTeX 和 LuaLaTeX 具有完整的 unicode 支持,可以使用安裝在操作系統中的任何字體,利用 OpenType,AAT 和 Graphite 的高級排版功能。 由`plt.savefig('figure.pgf')`創建的 Pgf 圖片可以作為原始命令嵌入到 LaTeX 文檔中。 圖形也可以通過切換到該后端,直接編譯并使用`plt.savefig('figure.pdf')`保存到 PDF。
```py
matplotlib.use('pgf')
```
或者為處理 PDF 輸出而注冊它:
```py
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
```
第二種方法允許你繼續使用常規的交互式后端,并從圖形用戶界面保存 xelatex,lualatex 或 pdflatex 編譯的 PDF 文件。
Matplotlib 的 pgf 支持需要最新的 [LaTeX](http://www.tug.org/) 安裝,包括 TikZ/PGF 軟件包(如 [TeXLive](http://www.tug.org/texlive/)),最好安裝 XeLaTeX 或 LuaLaTeX。 如果你的系統上存在 pdftocairo 或 ghostscript,也可以選擇將圖形保存為 PNG 圖像。 所有應用程序的可執行文件必須位于[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)中。
控制 pgf 后端行為的 Rc 參數:
| 參數 | 文檔 |
| --- | --- |
| `pgf.preamble `| 包含在 LaTeX 序言中的行 |
| `pgf.rcfonts` | 使用 fontspec 軟件包從 rc 參數設置字體 |
| `pgf.texsystem` | `xelatex`(默認),`lualatex`或者`pdflatex` |
> 注意
> TeX 定義了一系列特殊字符,例如:
> ```
> # $ % & ~ _ ^ \ { }
> ```
> 通常,這些字符必須正確轉義。一些字符(`_`,`^`,`%`)會自動在數學環境之外轉義。
## 字體規定
用于獲取文本元素大小,或將圖形編譯為 PDF 的字體通常在 matplotlib rc 參數中定義。 你還可以通過清除`font.serif`,`font.sans-serif`或`font.monospace`的列表來使用 LaTeX 默認的 Computer Modern 字體。 請注意,這些字體的字形覆蓋范圍非常有限。 如果要保留 Computer Modern 字體,但需要擴展 Unicode 編碼支持,請考慮安裝 [Computer Modern Unicode](https://sourceforge.net/projects/cm-unicode/) 字體 CMU Serif,CMU Sans Serif 等。
保存到`.pgf`時,matplotlib 用于圖形布局的字體配置包含在文本文件的標題中。
```py
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_rc_fonts = {
"font.family": "serif",
"font.serif": [], # use latex default serif font
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
}
mpl.rcParams.update(pgf_with_rc_fonts)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.text(2.5, 1., "comic sans", family="Comic Sans MS")
plt.xlabel(u"μ is not $\\mu$")
plt.tight_layout(.5)
```

## 自定義序言
通過將你的命令添加到序言中,你可以完全自定義它。 如果要配置數學字體(例如使用 unicode-math)或加載其他軟件包,請使用`pgf.preamble`參數。 此外,如果你想自己做字體配置,而不是使用 rc 參數中指定的字體,請確保禁用`pgf.rcfonts`。
```py
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import matplotlib as mpl
mpl.use("pgf")
pgf_with_custom_preamble = {
"font.family": "serif", # use serif/main font for text elements
"text.usetex": True, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fonts from rc parameters
"pgf.preamble": [
"\\usepackage{units}", # load additional packages
"\\usepackage{metalogo}",
"\\usepackage{unicode-math}", # unicode math setup
r"\setmathfont{xits-math.otf}",
r"\setmainfont{DejaVu Serif}", # serif font via preamble
]
}
mpl.rcParams.update(pgf_with_custom_preamble)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.xlabel("unicode text: я, ψ, €, ü, \\unitfrac[10]{°}{μm}")
plt.ylabel("\\XeLaTeX")
plt.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"])
plt.tight_layout(.5)
```

## 選擇 TeX 系統
matplotlib 使用的 TeX 系統由`pgf.texsystem`參數選擇。 可能的值為`xelatex`(默認值),`lualatex`和`pdflatex`。 請注意,當選擇`pdflatex`時,必須在序言中配置字體和 unicode 處理。
```py
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_pdflatex = {
"pgf.texsystem": "pdflatex",
"pgf.preamble": [
r"\usepackage[utf8x]{inputenc}",
r"\usepackage[T1]{fontenc}",
r"\usepackage{cmbright}",
]
}
mpl.rcParams.update(pgf_with_pdflatex)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif", family="serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.xlabel(u"μ is not $\\mu$")
plt.tight_layout(.5)
```

## 故障排除
請注意,在一些 Linux 發行版和 MiKTeX 安裝中發現的 TeX 包已經過時了。確保更新你的軟件包目錄并升級或安裝最新的 TeX 發行版。
在 Windows 上,可能需要修改[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)環境變量來包含 latex,dvipng 和 ghostscript 可執行文件的目錄。詳細信息請參閱[環境變量](http://matplotlib.org/faq/environment_variables_faq.html#environment-variables)和[在窗口中設置環境變量](http://matplotlib.org/faq/environment_variables_faq.html#setting-windows-environment-variables)。
Windows 上的限制會導致后端保留由應用程序打開的文件句柄。因此,可能無法刪除相應的文件,直到應用程序關閉(參見[`#1324`](https://github.com/matplotlib/matplotlib/issues/1324))。
有時保存到 png 圖像的圖形中的字體非常糟糕。這在 pdftocairo 工具不可用,并且 ghostscript 用于 pdf 到 png 的轉換時發生。
確保你想要做的事情在 LaTeX 文檔中可實現,你的 LaTeX 語法是有效的,并且你正在使用原始字符串,如果必要的話,避免意外的轉義序列。
`pgf.preamble rc`設置提供了大量的靈活性,以及導致問題的許多方法。遇到問題時,嘗試最小化或禁用自定義序言。
配置 unicode-math 環境可能有點棘手。例如 TeXLive 分發版提供了一組通常不在系統范圍內安裝的數學字體。與 LuaLatex 不同的是,XeTeX 不能根據名字找到這些字體,這就是你可能必須指定`\setmathfont{xits-math.otf}`,而不是`\setmathfont{XITS Math}`的原因,或者使字體可用于你的操作系統。更多詳細信息請參閱這個[`tex.stackexchange.com`的問題](http://tex.stackexchange.com/questions/43642)。
如果 matplotlib 使用的字體配置不同于你的 LaTeX 文檔中的字體設置,則導入圖形中的文本元素對齊可能會關閉。如果你不確定 matplotlib 用于布局的字體,請檢查`.pgf`文件的標題。
如果圖中有很多對象,矢量圖像和`.pgf`文件可能變得臃腫。這可能是圖像處理或非常大的散點圖的情況。在極端情況下,這可能導致 TeX 內存不足:`TeX capacity exceeded, sorry`(TeX 容量過大,對不起)。你可以配置 LaTeX 來增加可用于生成`.pdf`圖像的內存量,請見[`tex.stackexchange.com`](http://tex.stackexchange.com/questions/7953)上討論的問題。另一種方法是使用`rasterized = True`關鍵字,或者根據[本示例](http://matplotlib.org/examples/misc/rasterization_demo.html)的`.set_rasterized(True)`『柵格化』圖形的某些導致問題部分。
如果你仍需要幫助,請參閱[獲取幫助](http://matplotlib.org/faq/troubleshooting_faq.html#reporting-problems)。