LoginSignup
200
149

More than 5 years have passed since last update.

Python 3.3でmatplitlibとpylabを使おうとしたら RuntimeError: Python is not installed as a frameworkというエラーが発生したときの解決方法

Posted at

経緯

  • pyenv
  • virtualenv
  • Python 3.3.1

で、Scikit-learnを使った機械学習をやろうと思い立った。ついでに図の可視化もやろうと考えてmatplotlibも使うことにした。matplotlibを簡単に使うためにpylabをimportしたところ、RuntimeError: Python is not installed as a frameworkというエラーが発生したので、matplotlibの設定を変えて、問題を解決した。

インストール手順

$ pip install scikit-learn
$ brew install freetype
$ sudo pip install python-dateutil
$ sudo pip install pyparsing
$ sudo pip install matplotlib

matplotlibのインストールには

  • freetype
  • python-deteutil
  • pyparsing

が必要。ほかにも色々必要なものがある。詳しくは公式ページにて

なお、freetypeをbrew installしたら依存しているlibpngも入る。

参考 http://djakarta-trap.net/blog/2013/06/07/install_matplotlib/

問題発生

対話環境で

ipython3
import pylab

とすると

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.

なるエラーが発生した。

調査

まず同様のエラーが起こって困っている人、そして解決した人がいないか調べた。

ytというmatplotlibを利用したプロジェクトでの議論 http://hg.yt-project.org/yt/issue/642/cannot-import-pylab-on-os-x-using

同じ問題にぶつかった日本語ブログ記事 http://asahima.hatenablog.com/entry/2013/10/11/201119

matplotlib本家githubでのissue https://github.com/matplotlib/matplotlib/issues/2361

どうも2013年10月段階でもまだ解決していないみたい。

原因

matplotlibの画像描画バックエンド(参考 http://matplotlib.org/faq/usage_faq.html#what-is-a-backend )はデフォルトの設定ではCocoaのAPIを使ってレンダリングを行う"macosx"である。デフォルトではないバックエンドとしてGTKAggやQt4Aggがある。LinuxやWindowsから使うときは当然macosx以外のバックエンドを設定する。

僕の推論

※(この項の内容は想像で考えたことなので、間違っている可能性があります)

問題は、僕の環境ではpyenvを使ってOSXシステムにもとから入っているのとは違う場所にPython 3.3をインストールしていたことだ。この場合、CocoaのAPIで描画できない可能性があるので、pylabをimportしたときに、念のためにエラーを発生させてしまう。

※(推論終わり)

バックエンドをmacosx以外のものに指定すれば、問題は解決する。

解決方法

matplotlibをpipでインストールしたので、 ~/.matplotlib というディレクトリができているはずだ。そこにmatplotlibrcというファイルを作る。

~/.matplotlib/matplotlibrc
backend : TkAgg

と、TkAggをバックエンドに使うよう指定する。

matplotlibrcの書き方参考 http://matplotlib.org/users/customizing.html

実験

こちらのブログ記事 http://sucrose.hatenablog.com/entry/2013/05/25/133021 にて紹介されている、sklearnの結果をpylabで可視化するコードを対話環境で実行した。

from sklearn.datasets import load_digits
import pylab as pl 
digits = load_digits()
pl.gray() 
pl.matshow(digits.images[0]) 
pl.show() 

figure_2.png

このように、TkAggでもきれいに図を描画できた。

200
149
1

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
200
149