0
0

【Python】sympyの行列をlatex(matplotlib)で表示する

Last updated at Posted at 2023-09-25

概要

sympyは代数の計算を行うことができる標準ライブラリです。
sympy.latex()関数を用いることで簡単に計算式のlatexコマンドを得ることができますが、行列のlatexコマンドをmatplotlibで表示したところエラーが発生したため、その原因と解決策を書き残しておきます。

エラー

行列式を代入しlatex()でlatexコマンドへ変換した後、matplotlibでその数式を表示します。
from sympy import symbols, Matrix, latex
import matplotlib.pyplot as plt

#xを入力時のシンボルとして指定
x = symbols('x')

#行列を定義
matrix = symbols("a:z", Integer=True)
matrix = Matrix()
m = Matrix([
    [x**3 + 2, x - 2],
    [2*x + 3, x**2 - x + 4]])

#mをlatexに変換
m = latex(m)

#図を定義
plt.rcParams["text.usetex"] = True
fig, ax = plt.subplots()
tex1 = m
ax.axis('off')
ax.text(0.5, 0.5, m, ha='center', va='center', fontsize=15)

#式の表示
plt.show(fig)

しかし、上記を実行すると下記の様なランタイムエラーとなってしまいました。

出力結果
RuntimeError: latex was not able to process the following string:
b'\\\\left[\\\\begin{matrix}x^{3} + 2 & x - 2\\\\\\\\2 x + 3 & x^{2} - x +4\\\\end{matrix}\\\\right]'
Here is the full command invocation and its output:
latex -interaction=nonstopmode --halt-on-error --output-directory=tmp2rn45omx 704bb5753e3d22277de033293f40157c.tex
This is pdfTeX, Version 3.141592653-2.6-1.40.25 (TeX Live 2023) (preloaded format=latex)
 restricted \write18 enabled.
entering extended mode
....

原因

エラーコードにはlatexの記法が間違っていると書かれていますが、厳密には

sympy.latex() の戻り値はamsmathパッケージが使用された記法であり、デフォルトのmatplotlibではそのパッケージが有効になっていないためエラーを引き起こしています。

解決策

text.latex.preambleの設定からamsmathパッケージを有効にすることでエラーを防ぐことができます。
m = r"$" + latex(m) + r"$"

plt.rcParams["text.usetex"] = True
plt.rcParams["text.latex.preamble"] = r"\usepackage{amsmath}"


出力結果
スクリーンショット 2023-09-25 234436.png

また拡張子.mplstyleに設定を保存し、それを呼び出すことでも有効にできます。

plt.style.use(['スタイル名'])

参考:

おわりに

どこかでmatplotlibのlatex表記ではパッケージを利用できないという記述を見つけました。だからわざわざamsmath表記を数式モード表記に置換するというコードを書いたにも拘わらず、後からパッケージの使い方を知り無駄になってしまいました。 これを見て皆さんが同じ羽目に遭わないといいなと思います。
0
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
0
0