# Python3でmatplotlibを使おうとしたらハマったので解決法の備忘録 環境は以下の通り。 ``` MacOS 10.13 High Sierra Python3(3.7.0) ``` ## Pythonのインストール手順 なんでエラーが起きたのか今後の為に一応インストール手順を記します。 1. homebrewのインストール 1. homebrewでpython3をインストール 1. homebrewでpyenvをインストール 1. pyenvのコマンドを使えるようにパスを通す 1. python3系のバージョンを選択してインストール 1. インストールしたpythonのバージョンに切り替え 1. pip3を使って諸々のライブラリ(numpy, matplotlibなど)をインストール てな感じです。この辺を参考にしました。 [MacにPython3をインストールする方法](https://hajipro.com/python/mac-python3) いやあ、Unix系の環境構築の楽さが沁みる。Windowsだったら倍の時間かかってただろう。 この辺はやっぱりMacが強い。 ### 謎のエラー と言うことで、早速グラフをプロットしてみようと以下のコードを実行してみた。 ```python import matplotlib.pyplot as plt import numpy as np # データ生成 x = np.linspace(0, 10, 100) y = x + np.random.randn(100) # プロット plt.plot(x, y, label="test") # 凡例の表示 plt.legend() # プロット表示(設定の反映) plt.show() ``` すると以下のエラーを吐き出した。 ```python Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/UserName/.pyenv/versions/3.7.0/lib/python3.7/site-packages/matplotlib/pyplot.py", line 115, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Users/UserName/.pyenv/versions/3.7.0/lib/python3.7/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/Users/UserName/.pyenv/versions/3.7.0/lib/python3.7/site-packages/matplotlib/backends/backend_macosx.py", line 17, in <module> from matplotlib.backends import _macosx RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information. ``` これは原因がさっぱり全然わからない。 しかし、TracebackとかRuntimeErrorで調べるとバックエンドの問題が発生しているそうな。僕には分からないけど。 ### 解決法 ```c $ python -c "import matplotlib;print(matplotlib.matplotlib_fname())" ``` とターミナルに打ち込んで、matplotlibrcという名のファイルを探す。 このファイルをエディタで開き、35~40行目あたりにある ``` backend : macosx ``` を ``` backend : TkAgg ``` に変更すると良いそうだ。 実際にやってみたら治った。 めでたしめでたいし。 <img src="https://cdn-ak.f.st-hatena.com/images/fotolife/t/tanisuke_str/20180704/20180704205505.png"> <span style="color:#d4d4d4; text-align:center;">実際にプロットできた様子 </span>