理解fig,ax = plt.subplots()

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])

原文地址:https://www.cnblogs.com/komean/p/10670619.html