【第2回】Pythonではじめるディープラーニング
今回はグラフ表示ライブラリ(Matplotlib)のセットアップについてまとめました。
Matplotlibのインストール
Matplotlibをインストールします。
pip3 install matplotlib
Matplotlibの実行
Jupyter notebook(IPython)でMatplotlibを実行するには%matplotlib
マジックを使用します。過去の方法では名前空間を汚染してしまうため、このマジックを使用します。
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# Note that using plt.subplots below is equivalent to using
# fig = plt.figure() and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
plt.show()
Jupyter notebook(IPython)でプログラムを実行するとブラウザ上にグラフが表示されます。
Tkinterのインストール
PythonでMatplotlibを実行できるように、Tkinterをインストールします。
apt install python3-tk
Matplotlibにはバックエンドと呼ばれるものがあり、異なる出力先を設定できます。use()
関数はmatplotlib.pyplot
をインポートする前に実行してください。AggはAnti-Grain Geometryと呼ばれるレンダリングエンジンで、高品質のイメージをレンダリングできます。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
次のプログラムを作成して、Pythonで実行するとtest.png
が作成されます。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# Note that using plt.subplots below is equivalent to using
# fig = plt.figure() and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
test.png
Matplotlibの設定
設定ファイルは~/.config/matplotlib/matplotlibrc
に作成します。
wget 'https://matplotlib.org/_static/matplotlibrc'
設定ファイルをダウンロードして、バックエンドをAgg
に変更します。これでuse()
関数は不要になります。
#backend : qt5agg
backend : Agg
参考文献
- Installing — Matplotlib 2.2.2 documentation
- Using matplotlib in a python shell — Matplotlib 2.2.2 documentation
- Simple Plot — Matplotlib 2.2.2 documentation
- Usage — Matplotlib 2.0.2 documentation
- Customizing matplotlib — Matplotlib 2.0.2 documentation
- python - _tkinter.TclError: no display name and no $DISPLAY environment variable - Stack Overflow