■インポート
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
matplotlibの
gridspec を追加でインポート
以降の呼び出し簡略化のため「gridspec」と名前を付ける
■複数のグラフを描写
・表示用データ
#-10~10
lsX = range(-10, 11)
#-10~10の2乗
lsY = [a**2 for a in range(-10, 11)]
・下地作成
fig = plt.figure(tight_layout=True)
fig.suptitle('fig title')
plt.show()
plt.figure() でインスタンス作成
tight_layout=True を指定しておくとグラフが重なって描写されるのを防ぐ
fig.suptitle() でタイトルを追加
・分割数を指定
gs = gridspec.GridSpec(3, 3)
gridspec.GridSpec(行数, 列数) で行数と列数を指定してインスタンス作成
・位置を指定してグラフを描写
fig = plt.figure(tight_layout=True)
fig.suptitle('fig title')
gs = gridspec.GridSpec(3, 3)
ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(lsX, lsY)
ax1.set_title('plot')
ax2 = fig.add_subplot(gs[1, 2])
ax2.bar(lsX, lsY)
ax2.set_title('bar')
ax3 = fig.add_subplot(gs[2, 0])
ax3.scatter(lsX, lsY)
ax3.set_title('scatter')
plt.show()
fig.add_subplot() で描写する位置を指定してインスタンス作成
位置は
gs[行, 列] で指定(
0 始まり)
後はインスタンスから
.plot() などでグラフを描写
fig = plt.figure(tight_layout=True)
fig.suptitle('fig title')
gs = gridspec.GridSpec(3, 3)
ax1 = fig.add_subplot(gs[0:2, 0:2])
ax1.plot(lsX, lsY)
ax1.set_title('plot')
ax2 = fig.add_subplot(gs[0:2, 2])
ax2.bar(lsX, lsY)
ax2.set_title('bar')
ax3 = fig.add_subplot(gs[2, :])
ax3.scatter(lsX, lsY)
ax3.set_title('scatter')
plt.show()
gs[行, 列] は「
: 」を使って範囲を指定できる
※「n:m」は「n以上m未満」の範囲、「:」だけ指定すると全範囲となる
・分割範囲の大きさを比率で指定する
fig = plt.figure(tight_layout=True)
fig.suptitle('fig title')
gs = gridspec.GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[3, 1])
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(lsX, lsY)
ax1.set_title('plot')
ax2 = fig.add_subplot(gs[1, 1])
ax2.bar(lsX, lsY)
ax2.set_title('bar')
plt.show()
gridspec.GridSpec() に
height_ratios=[] (縦方向)、
width_ratios=[] (横方向)で分割の比率を指定
■おまけ
・axesインスタンスのグラフ装飾
fig = plt.figure(tight_layout=True)
fig.suptitle('fig title')
gs = gridspec.GridSpec(1, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(lsX, lsY, color='red', label='y')
ax1.set_title('plot')
ax1.set_xlabel('x-label')
ax1.set_ylabel('y-label')
ax1.legend()
ax1.grid()
ax2 = fig.add_subplot(gs[0, 1])
ax2.bar(lsX, lsY, color='blue', label='y')
ax2.set_title('bar')
ax2.legend()
ax2.tick_params('x', labelrotation=45)
ax2.yaxis.set_ticks([])
plt.show()