LoginSignup
8
7

More than 5 years have passed since last update.

Pythonでmatplotlibの描画がうまく機能しない場合の対処

Last updated at Posted at 2016-08-08

はじめに

Anaconda経由でインストールしたはずが、描画がうまくいかないmatplotlibの対処が簡単ですが、案外ハマったので、紹介しておきます。

開発環境

・OS: Mac OS X EI Capitan (10.11.5)
・Python 2.7.12: Anaconda 4.1.1 (x86_64)

失敗例

まず対話型のpythonを開きます。

$ python

ここで、matplotlibの簡単な描画サンプルを打ち込んでみます。

>>> import matplotlib.pyplot as plt
objc[10813]: Class TKApplication is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Users/{my_user_name}/anaconda2/lib/libtk8.5.dylib. One of the two will be used. Which one is undefined.
objc[10813]: Class TKMenu is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Users/{my_user_name}/anaconda2/lib/libtk8.5.dylib. One of the two will be used. Which one is undefined.
objc[10813]: Class TKContentView is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Users/{my_user_name}/anaconda2/lib/libtk8.5.dylib. One of the two will be used. Which one is undefined.
objc[10813]: Class TKWindow is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Users/{my_user_name}/anaconda2/lib/libtk8.5.dylib. One of the two will be used. Which one is undefined.

>>> plt.plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x10f365a90>]

>>> plt.show()
Exception in Tkinter callback
Traceback (most recent call last):
  File "/Users/{my_user_name}/anaconda2/lib/python2.7/lib-tk/Tkinter.py", line 1537, in __call__
    return self.func(*args)
  File "/Users/{my_user_name}/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 283, in resize
    self.show()
  File "/Users/{my_user_name}/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 355, in draw
    tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
  File "/Users/{my_user_name}/anaconda2/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 30, in blit
    id(data), colormode, id(bbox_array))
TclError

このように、エラーがでて、matplotlibのimportが通り、描画用のGUIが表示されるも、実際の描画処理はうまくいっていないことがわかります。

スクリーンショット 2016-08-08 11.09.10.png

解決策

下記のファイルを編集することで解決しました。

vim ~/.matplotlib/matplotlibrc

このファイル内の
backend: TkAgg
となっている部分を
backend : Qt4Agg
に変更すればOKです。

変更後、同様にmatplotlibの簡単な描画サンプルを打ち込んでみます。

$ python
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3,4])
>>> plt.show()

スクリーンショット 2016-08-08 11.16.40.png

これでうまく描画することができました。

参考

Why is pyplot giving me a TclError on osx?
matplotlibでグラフ表示できない [解決]

おまけ

フォローお待ちしています!
Qiita: Carat 吉崎
twitter:@carat_yoshizaki
はてなブログ:Carat COOのブログ

機械学習をマンツーマンで学べる家庭教師サービス「キカガク
「数学→プログラミング→Webアプリケーション」まで一気に学べる「キカガク」に興味のある方はお気軽にご連絡ください。

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