LoginSignup
4
6

More than 5 years have passed since last update.

【第2回】Pythonではじめるディープラーニング

Posted at

【第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

test.png

Matplotlibの設定

設定ファイルは~/.config/matplotlib/matplotlibrcに作成します。

wget 'https://matplotlib.org/_static/matplotlibrc'

設定ファイルをダウンロードして、バックエンドをAggに変更します。これでuse()関数は不要になります。

#backend      : qt5agg
backend      : Agg

参考文献

4
6
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
4
6