参考:matplotlib图形整合之多个子图一起绘制_matplotlib多子图_王小王-123的博客-CSDN博客
方式一:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
# 方式一: gridspec
# rowspan:行的跨度,colspan:列的跨度
# 第一格
ax1=plt.subplot2grid((3,3),(0,0), colspan=3, rowspan=1)
ax1.plot([1,2],[1,4])
ax1.set_xlabel("xlabel")
ax1.set_ylabel("ylabel")
ax1.set_title("ax1_title")
# ax1.set_xlim(0,4)
# ax1.set_ylim(0,6)
ax1.grid()
# 第二格
ax2=plt.subplot2grid((3,3),(1,0), colspan=2, rowspan=1)
# 第三格
ax3=plt.subplot2grid((3,3),(1,2), rowspan=2)
# 第四格
ax4=plt.subplot2grid((3,3),(2,0))
# 第五格
ax4=plt.subplot2grid((3,3),(2,1))
plt.tight_layout()
plt.show()
显示结果:
方式二:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# 方式二: easy to define structure
plt.figure(num=33)
gs = gridspec.GridSpec(3,3)
x11 = plt.subplot(gs[0,:]) # gs[0, :] 从第1行(索引0)开始,占了所有列(:)
x11.set_title("gs[0, :]")
x21 = plt.subplot(gs[1,:2]) # gs[1, :2] 从第2行(索引1)开始,占了前2列(:2)
x21.set_title("gs[1,:2]")
x22 = plt.subplot(gs[1:,2]) # gs[1:, 2] 从第2行(1:)开始占了之后的所有行(2,3行),占了第3列(索引2)
x22.set_title("gs[1:,2]")
x31 = plt.subplot(gs[-1,0]) # gs[-1, 0] 该子图占了第3行(索引-1),第1列(0)
x31.set_title("gs[-1,0]")
x32 = plt.subplot(gs[-1,-2]) # gs[-1, -2] 该子图占了第3行(-1),第2列(-2)
x32.set_title("gs[-1,-2]")
plt.tight_layout()
plt.show()
显示结果
方式三:
import matplotlib.pyplot as plt
fig, ((ax11,ax12,ax13),(ax21,ax22,ax23),(ax31,ax32,ax33)) = plt.subplots(3,3,sharex=True,sharey=True)
ax11.scatter([1,2],[1,4])
ax12.plot([1,2,3,4],[1,4,9,16])
plt.tight_layout()
plt.show()
显示结果: