Matplotlibでよく使う文法 まとめ

インポート

import matplotlib.pyplot as plt

モジュールであるmatplotlibのpyplotをインポートする必要があります。

複数のグラフ

fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(縦の図数,横の図数,1)
ax2=fig.add_subplot(縦の図数,横の図数,2)
ax3=fig.add_subplot(縦の図数,横の図数,3)
....

1枚に複数のグラフの表示する際に用います。1つのグラフでも可。

add_subplotの第一引数は、縦の図数、第二引数は、横の図数、第三引数は、どこの図であるかを表します。

figsizeは、省略可能です。

例1 3×1の図

fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(3,1,1)
ax2=fig.add_subplot(3,1,2)
ax3=fig.add_subplot(3,1,3)

例2 2×2の図

fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)

グラフの表示

plt.show()

なお、 JupyterNotebook では、省略可能です。

折れ線グラフ

plt.plot(x,y)

subplotした場合

ax.plot(x,y)

散布図

plt.scatter(x,y)

subplotした場合

ax.scatter(x,y)

ヒストグラム

plt.hist(x)

subplotした場合

ax.hist(x)

円グラフ

plt.pie(x)

subplotの場合

ax.pie(x)

タイトル

plt.title("Title name")

subplotの場合

ax.set_title("Title name")

軸ラベル

plt.xlabel("label name")
plt.ylabel("label name")
ax.set_xlabel("label name")
ax.set_ylabel("label name")

凡例

plt.plot(x,y,label="sample01")
plt.legend()

subplotの場合

ax.plot(x,y,label="sample02")
plt.legend()

グリット

plt.grid()

subplotの場合

ax.grid()

軸範囲

plt.xlim(初め、終わり)
plt.ylim(初め、終わり)

subplotの場合

ax.set_xlim(初め、終わり)
ax.set_ylim(初め、終わり)

目盛り間隔

plt.xticks(リストや配列)
plt.yticks(リストや配列)
ax.set_xticks(リストや配列)
ax.set_yticks(リストや配列)

まとめ

subplotするかしないかで文法が少し違います。

いつもそこらへんが混乱するので、1つの図を描く際も、fig.add_subplot(1,1,1)として、subplotの方を使うのがよいのかなと個人的には思っています。