madokaのブログ

勉強したことのoutput先として使ってます。内容はpythonがらみが多いかもです。

pyenv+matplotlibで発生するエラーを回避する

タイトルの通り、pyenvで取得したpythonでmatplotlibを使おうとしたときの話です。

  • macOS Mojave 10.14.6
  • Homebrew 2.2.11
  • pyenv 1.2.15
  • python 3.7.5
import matplotlib.pyplot as plt
...
plt.show()

このようなグラフ表示を伴うコードを書くと以下のようなエラーが発生します。

...(省略)
ImportError: 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.

このエラーで検索をかけると大体が、~/.matplotlib/matplotlibrc

"backend" : "TkAgg"

を追加してくださいという記述が見つかります。これはグラフの表示にTkinterを使うという指定をしており、これで上記のエラーが発生しなくなるのはpython3はインストール時にtkinterも(基本は)同梱しているからです。しかし、pyenvを使用しているとうまくいかない場合があります。実際にわたしの環境では以下のエラーが発生しました。

...(省略)
import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named ‘_tkinter’

どうやらtkinterがないと言っているようなのです。 pyenvでpythonをインストールした時にtkinterがうまく入らなかったということになります。実際にそう言った症例もネットで見つかりました。 Python not configured for Tk - Stack Overflow ここではpyenvでpythonをインストールする時に必要なものが書かれていました。zlib、tcl-tkが必要だそうです。

brew install zlib
brew install tcl-tk

以上でインストールしましょう。 上記のページでは、この後にpyenvをインストールするよう書いてありましたが、わたしの場合はそのままでも大丈夫でした。 この操作が終わった後にpyenvでのpythonのインストールするとtkinterが入っているので、あとは先ほどのmatplotlibrcの設定があればmatplotlibの描画にtkinterを使えるようになります。

ちなみにこれを入れただけでもtkinterがうまく入らないというケースもあるようで、その場合は.bashrcにパスを記入する必要があるみたいです。 pyenv install doesn't work with homebrew installed tcl-tk · Issue #1375 · pyenv/pyenv · GitHub

おまけ

わたしはこれからさらに仮想環境を作ってやっていたのですが、その場合はホームディレクトリは汚したくないので、仮想環境の方にmatplotlibrcの設定を書きました。以下を仮想環境のpythonで実行すれば、matplotlibrcのファイルの場所がわかります。

import matplotlib
matplotlib.matplotlib_fname()

まとめ

matplotlibの仕様とpyenvの仕様?が絡んでいる問題だったので、解決まで時間がかかりました。。pyenvのこと信頼しきっていたけど、こんな問題があったとはと驚かされた事件でした。