2020年4月27日月曜日

【matplotlib】グラフ作成、タイトル・ラベル・凡例・グリッドの表示

グラフ描画ライブラリ matplotlib を用いると様々なグラフが作成できる。グラフ作成には matplotlib.pyplot モジュールを使用する。

matplotlibを使うにはインポートが必要。 matplotlib.pyplot は通常以下の書式でpltと略されインポートされる。

import matplotlib.pyplot as plt


1. グラフ作成

グラフを作成するには plt.plot メソッドで、引数x,yを与え、 plt.show() とするとグラフが表示される。

次の例では0から5まで0.1刻みの値を持つ ndarray を生成しそれをxに、sin(x)をyとしてグラフを描画する。

コード

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)

plt.plot(x, y)
plt.show()

実行結果



2. 軸ラベル・グラフタイトルの表示

x軸のラベルを表示する場合は plt.xlabel 、y軸のラベルを表示する場合は plt.ylabel を指定する。

コード

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

実行結果



グラフタイトルを表示する場合は plt.title を指定する。

コード

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)

plt.plot(x, y)
plt.title('sin curve')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

実行結果



3. 複数系列と凡例の表示

グラフに複数系列を表示するには plt.plot を系列の数だけ用意すればよい。
y_2としてcos(x)を追加した場合。

コード

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
y_2 = np.cos(x)

plt.plot(x, y)
plt.plot(x, y_2)
plt.title('sin curve')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()

実行結果



凡例に系列名を表示するには plt.plot の引数として label を指定したうえで plt.legend() とする。

コード

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
y_2 = np.cos(x)

plt.plot(x, y, label='sin curve')
plt.plot(x, y_2, label='cos curve')
plt.title('sin curve')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.legend()
plt.show()

実行結果



4. グリッド(目盛り)の表示

 グリッドを表示するには plt.gridとする。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
y_2 = np.cos(x)

plt.plot(x, y, label='sin curve')
plt.plot(x, y_2, label='cos curve')
plt.title('sin curve')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.legend()
plt.show()

実行結果



5. リファレンス

matplotlib > matplotlib.pyplot
matplotlib > matplotlib.pyplot.show
matplotlib > matplotlib.pyplot.xlabel
matplotlib > matplotlib.pyplot.ylabel
matplotlib > matplotlib.pyplot.title
matplotlib > matplotlib.pyplot.legend
matplotlib > matplotlib.pyplot.grid

使用バージョン:Python 3.7.0 / matplotlib 3.2.1

0 件のコメント:

コメントを投稿