1
0

More than 3 years have passed since last update.

Matplotlibのスタイルシートにおけるtext.latex.preambleの書き方

Posted at

目的

Matplotlibでは、図の体裁を制御するための様々なパラメータがありますが、それらは設定ファイルの形で一括で指定することができます。(スタイルファイルのサンプルは公式サイトで公開されています。)その設定項目のひとつに、text.latex.preamble というものがあります。ここにLaTeXパッケージ名をしかるべき書式で記述すると、それらが読み込まれた上でレンダリングが行われます。しかしながら、この項目はUNSUPPORTED扱いであり、詳しい書き方は説明されていません。(「一行で書け」とだけ注意されています。)この記事ではその書き方の例を示します。

環境

>>> conda info
          conda version : 4.5.11
    conda-build version : 3.0.9
         python version : 3.5.6.final.0
               platform : win-64
             user-agent : conda/4.5.11 requests/2.18.4 CPython/3.5.6 Windows/10 Windows/10.0.18362

>>> conda list
# Name                    Version                   Build  Channel
matplotlib                2.0.2               np112py35_0
numpy                     1.12.1                   py35_0

>>> latex --version
pdfTeX 3.14159265-2.6-1.40.16 (TeX Live 2015/W32TeX)
kpathsea version 6.2.1

サンプル

matplotlibrc file (パラメータを設定するファイル)の例です。text.latex.preambleには、読み込みたいパッケージや自作コマンドの定義を一行で書きます。区切りは空白でもコンマでもOK。\のエスケープは不要です。

sample.mplstyle
text.usetex         : True
text.latex.preamble : \usepackage{amsmath}, \usepackage{amssymb} \usepackage{physics} \newcommand{\hH}{\hat{H}} \newcommand{\hc}{\hat{c}}

これを用いた描画スクリプトの例です。ラベルには特に意味はありません。

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np

def main():
    X = np.arange(0, np.pi, 0.01)
    Y = [np.sin(x) for x in X]

    with plt.style.context('sample.mplstyle'):
        plt.figure()
        plt.plot(X, Y, label=r'$\int \dd{x} \sin x$')
        plt.xlabel(r'$\mathbb{R}, \ (x+y)^n = \sum_{i=0}^n \binom{n}{k} x^i y^{n-i}$')
        plt.ylabel(r'$\Im\ev{A}{\Psi}$')
        plt.tick_params()
        plt.title(r'$A = \begin{pmatrix} a_{11} & a_{1n} \\ a_{m1} & a_{mn} \end{pmatrix}$')
        plt.text(1.0, 0.4, r'$\hat{H} =  \sum_{p,\sigma} \qty(\frac{p^2}{2m} - \mu_\sigma)  \hc_{p,\sigma}^\dag \hc_{p,\sigma}$')
        plt.legend()
        plt.tight_layout()
        plt.savefig('demo.png')


if __name__ == "__main__":
    main()

実行結果です。
demo.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0