Matplotlibサブプロット
複数のプロットを表示
subplot()
関数を使用すると、1つの図に複数のプロットを描画できます。
例
2つのプロットを描画します。
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
結果:

subplot()関数
subplot()
関数は、図のレイアウトを記述する3つの引数を受け取ります。
レイアウトは行と列で構成され、最初と2番目の引数で表されます。
3番目の引数は、現在のプロットのインデックスを表します。
:::codeline {.techis-codeline .notranslate .language-python}
plt.subplot(1, 2, 1)
# 図には1行2列があり、このプロットは
最初のプロットです。
:::codeline
:::codeline {.techis-codeline .notranslate .language-python}
plt.subplot(1, 2, 2)
#図には1行2列があり、このプロットは
2番目プロットです。
:::codeline
したがって、2行1列の図が必要な場合(2つのプロットが並べて表示されるのではなく、重ねて表示されることを意味します)、次のような構文を書くことができます。
例
2つのプロットを重ねて描画します。
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
結果:

行数、列数、プロットのインデックスを指定するだけで、1つの図に好きなだけプロットを描くことができます。
例
6つのプロットを描画します。
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 6)
plt.plot(x,y)
plt.show()
結果:

タイトル
title()
関数を使用して各プロットにタイトルを追加できます。
例
タイトル付きの2つのプロット:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("セール")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("収入")
plt.show()
結果:

スーパータイトル
suptitle()
関数を使用して、図全体にタイトルを追加できます。
例
図全体のタイトルを追加します。
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("セール")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("収入")
plt.suptitle("私の店舗")
plt.show()
結果:

プログラミング学習を加速させる
プログラミングをプロの講師に教えてもらいませんか。