概要
Macのpyenv環境にあるpython2
でmatplotlib
を使う貰い物のコードを試していると、うまくいかない。
結果からいうと、pyside2
をインストールし、matplotlib
のコンフィグmatplotlibrc
を編集し、
backend osx
を
backend qt5agg
とすればうまくいった。
環境
Mac OSX 10.15.5
Python 2.7.17
(pyenvでインストール)
エラー内容
python-code.py
(仮名)を打つと下記の様なエラーが。
Traceback (most recent call last):
File "python-code.py", line 60, in <module>
import matplotlib.pyplot as plt
File "/Users/username/.pyenv/versions/2.7.17/lib/python2.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/2.7.17/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
[backend_name], 0)
File "/Users/username/.pyenv/versions/2.7.17/lib/python2.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.
読むと、
from matplotlib.backends import _macosx
あたりが示している様に、GUIのライブラリがダメらしい。
解決策
調べてみると、よくあるエラーの様で、解決策がいくつか出てきた。
Qt
を使うqt5agg
でうまくいきそうだが、もう一難。
python3
ではおなじみPyQt5
は、python2
ではつかえないらしい。
代わりの物はあるらしくpyside2
というらしい。
これを入れる。
pip install pyside2
そして、
python -c "import matplotlib;print(matplotlib.matplotlib_fname())"
で、matplotlibrc
(matplotのコンフィグファイル)のパスを調べて、42行目の
backend : macosx
をコメントアウトして、qt5agg
を加える。
# backend : macosx
backend : qt5agg
これで、無事目的の動作をした。
めでたし。
補足
なお、Tk
を使うTkagg
を試したが、うまくいかず。
参考
https://qiita.com/masatomix/items/03419c7ea10262da18f3
https://stackoverflow.com/questions/57238618/how-do-you-display-a-figure-in-matplotlib-using-pyside2