fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig, ax = plt.subplots(1,3),其中參數1和3分別代表子圖的行數和列數,一共有 1x3 個子圖像。函數返回一個figure圖像和子圖ax的array列表。 fig, ax = plt.subplots(1,3,1),最后一個參數1代表第一個子圖。 如果想要設置子圖的寬度和高度可以在函數內加入figsize值 fig, ax = plt.subplots(1,3,figsize=(15,7)),這樣就會有1行3個15x7大小的子圖。
控制子圖
方法1:通過plt控制子圖
方法2:通過ax控制子圖
# Creates two subplots and unpacks the output array immediately
fig = plt.figure()
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Creates four polar axes, and accesses them through the
# returned array
axes = fig.subplots(2, 2, subplot_kw=dict(polar=True))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
(1) 單行單列,按照一維數組來表示
# 定義fig
fig = plt.figure()
# 建立子圖
ax = fig.subplots(2,1) # 2*1
# 第一個圖為
ax[0].plot([1,2], [3,4])
# 第二個圖為
ax[1].plot([1,2], [3,4])
# 設置子圖之間的間距,默認值為1.08
plt.tight_layout(pad=1.5)
(2) 多行多列,按照二維數組來表示
# 定義fig
fig = plt.figure()
# 建立子圖
ax = fig.subplots(2,2) # 2*2
# 第一個圖為
ax[0,1].plot([1,2], [3,4])
# 第二個圖為
ax[0,1].plot([1,2], [3,4])
# 第三個圖為
ax[1,0].plot([1,2], [3,4])
# 第四個圖為
ax[1,1].plot([1,2], [3,4])