はじめに
CentOS7 上で Python 3.5.2 + Matplotlib 1.5.1 の環境で使用中、下記コードの2行目でエラーが発生しました。
(venv) $ python
Python 3.5.2 (default, Jul 27 2016, 20:30:25)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
Traceback (most recent call last):
File "", line 1, in
File "/home/user/plot/venv/lib/python3.5/site-packages/matplotlib/pyplot.py", line 527, in figure
**kwargs)
File "/home/user/plot/venv/lib/python3.5/site-packages/matplotlib/backends/backend_tkagg.py", line 84, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/home/user/plot/venv/lib/python3.5/site-packages/matplotlib/backends/backend_tkagg.py", line 92, in new_figure_manager_given_figure
window = Tk.Tk()
File "/opt/python3.5/lib/python3.5/tkinter/__init__.py", line 1867, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
対応
MatplotlibはGUI環境で実行されることをデフォルトの設定としている(※1)ようで、GUI環境がないWebアプリケーションサーバーなどでプロット結果を画像ファイルに保存するような、Window表示が不要となる状況ではpylabやpyplotをインポートする前に、1つ設定を追加する必要がある(※2)ようです。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
[参照] ドキュメントPDF(38.0MB)
※1 セクション4.3.2 Other python interpreters (ページ 27)
※2 セクション13.1.13 Generate images without having a window appear (ページ 403)、セクション13.3 Matplotlib in a web application server (ページ 406)
おわりに
同じCentOS7でもGUI環境ならこのエラーが出ず、GUI環境なしのアプリケーションサーバーやAWS AmazonLinuxサーバーで今回のエラーが出ていました。サーバーにもGUI環境が必要なのか、とも思いましたが、結果不要でほっとしました。困ったときのGoogle先生でもいいのですが、まずはマニュアルを確認してみると周辺の知識も蓄えられていいですね。