LoginSignup
0
0

More than 3 years have passed since last update.

python2.7でmatplotlibがうまくいかない時

Last updated at Posted at 2020-06-01

概要

Macのpyenv環境にあるpython2matplotlibを使う貰い物のコードを試していると、うまくいかない。

結果からいうと、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

0
0
0

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
0
0