前言
来自 莫烦python的总结。
均等分割
plt.figure()
plt.subplot(2,2,1) # 分成两行两列,第一个图
plt.plot([0,1],[0,1])
plt.subplot(2,2,2) # 分成两行两列,第二个图
plt.plot([0,1],[0,1])
plt.subplot(223) # 分成两行两列 不加逗号也ok
plt.plot([0,1],[0,1])
plt.subplot(2,2,4) # 分成两行两列,第四个图
plt.plot([0,1],[0,1])
不均等分割
方法一
这种方法其实是生成了两个figure,两个重叠从而改变排列方式
# figure1:生成一个2行1列的
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
# figure2:生成一个2行3列的figure
plt.subplot(2,3,4)
plt.plot([0,1],[0,1])
plt.subplot(2,3,5)
plt.plot([0,1],[0,1])
plt.subplot(2,3,6)
plt.plot([0,1],[0,1])
方法二 subplot2grid
plt.figure()
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) # 总共三行三列,ax1从(0,0)处数起占一行三列,其中的数字都是以行列的最小长度为单位
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title') # plt.title 变成 ax1.set_title
ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=1) # 其中的数字都是以行列的最小长度为单位
ax2.plot([1,2],[1,2])
ax2.set_title('ax2_title') # plt.title 变成 ax1.set_title
ax3 = plt.subplot2grid((3,3),(1,2),colspan=1,rowspan=2) # 其中的数字都是以行列的最小长度为单位
ax3.plot([1,2],[1,2])
ax3.set_title('ax3_title') # plt.title 变成 ax1.set_title
ax4 = plt.subplot2grid((3,3),(2,0),colspan=2,rowspan=2) # 其中的数字都是以行列的最小长度为单位
ax4.plot([1,2],[1,2])
ax4.set_title('ax4_title') # plt.title 变成 ax1.set_title
方法三 gridspec
import matplotlib.gridspec as gridspec
plt.figure()
# 类似于数组索引的方式
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])
方法四 subplots 有s哦
f,((ax11,ax12),(ax21,ax22))=plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])