Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【python】matplotlibでtex表記のlabelが表示されなくて困った

(2018/03/19 過去記事)

いろんな記事を見てみると、特別なことをしなくてもlabelにtex表記が使えるように書いてある

けどなんでか手元ではうまくいかない・・・

matplotlib以外に3次元プロットをするためのmpl_toolkitsも使ってるっぽいけど、
それは原因ではなさそう

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
「mpl_toolkits tex label」とか「mpl_toolkits greek label」とかで調べていくと、

■ 参考 : Text rendering With LaTeX

tex_demo.py にヒントがあった

"""
Demo of TeX rendering.

You can use TeX to render all of your matplotlib text if the rc
parameter text.usetex is set. This works currently on the agg and ps
backends, and requires that you have tex and the other dependencies
described at http://matplotlib.org/users/usetex.html
properly installed on your system. The first time you run a script
you will see a lot of output from tex and associated tools. The next
time, the run may be silent, as a lot of the information is cached in
~/.tex.cache

"""
import numpy as np
import matplotlib.pyplot as plt


# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

<span style="color: #ff0000;">plt.rc('text', usetex=True)</span>
<span style="color: #ff0000;">plt.rc('font', family='serif')</span>
plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)

plt.savefig('tex_demo')
plt.show()

赤色にした2行が大切
手元でテストしたらfontの方はなくてもきちんとTeX表記になったけど、
plt.rc('text', usetex=True)
を消すと、TeX表記が崩れて変なことになった
こっちが重要っぽい


ここにも似たようなことが書かれている↓

■ 参考 : Typing Greek letters etc. in Python plots



matplotlibで使えるTeX記号関連一覧

■ 参考 : Writing mathematical expressions

ランキング参加中です

↓クリックしていただけると嬉しいです〜