什么是gridspec
plt.GridSpec 是 Matplotlib 库中的一个函数,用于创建一个网格布局,可以将一个图形分成多个子图。它的强大之处在于能够创建跨越行和列的子图。
关于GridSpec的相关语法
GridSpec(nrows, ncols, figure=none, left=none, bottom=none, right=none, top=none, wspace=none, hspace= none, width_rations=none, height_rations=none)
具体参数设置如下
nrows:行数
ncols:列数
figure:表示布局的画布
hspace坐标系实例之间纵向间距
wspace坐标系实例之间横向间距
wspace,hspaec表示子图之间预留的宽度量,高度量
width_rations表示直接设置坐标系相对宽度,相对宽度=设定值/sum
height_rations表示直接设置坐标系相对高度,相对高度=设定值/sum
eft,bootom,right,top表示子图范围,把所有坐标实例打包在一起,整体伸缩/平移
简单了解了gridspes的参数,让我们做个实验练练手
1.导入所需模块
%matplotlib auto
#弹出窗绘图模式(将绘制的图表以弹出窗口的形式显示,支持用户交互、多种图片储存格式)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#导入所需库
2.添加画布
fig = plt.figure()
3.创建“区域规划图”实例
spec = gridspec.GridSpec(nrows=2, ncols=2, figure=fig)
4.根据给定的Gridspec实例,创建对应的坐标系实例
ax1 = fig.add_subplot(spec[0,0]) #二维数组的切片
#ax2 = fig.add_subplot(spec2[0,1]) 二维数组的索引
ax3 = fig.add_subplot(spec2[1,0])
ax4 = fig.add_subplot(spec2[0,1])
5.展示图表
plt.show()
完整代码
%matplotlib auto
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
spec = gridspec.GridSpec(nrows=2, ncols=2, figure=fig)
ax1 = fig.add_subplot(spec[0,0])
ax3 = fig.add_subplot(spec[1,0])
ax4 = fig.add_subplot(spec[0,1])
plt.show()
运行结果如下
在Gridspec中使用width_ratios和height_ratios参数。这些关键字参数是数字列表。
格式基本同上,具体代码如下
%matplotlib auto
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig2 = plt.figure(constrained_layout=True)
widths = [2,3,1.5]
heights = [1,3,2]
#绝对值是没有意义的,只有它们的相对比率重要 例 width_ratio =[2, 4, 8]与width_ratio =[1, 2, 4]在同样宽的数字内相等。
spec2 = fig2.add_gridspec(ncols=3,nrows=3,width_ratios=widths,height_ratios=heights)
for row in range(3):
for col in range(3):
ax = fig2.add_subplot(spec2[row,col])
label = 'Width: {}\nHeight: {}'.format(widths[col],heights[row])
ax.annotate(label,(0.1,0.5),xycoords='axes fraction',va='center')
plt.show()
运行结果如图所示
如何精细调整Gridspec布局
当显示地使用GridSpec时,可以通过改变gridspec的参数来调整子图的布局请注意,此选项与constrained_layout或者 Figure.tight_layout 都不兼容,两者都通过调整子图大小以填充figure。
参数请看:matplotlib.gridspec.GridSpec — Matplotlib 3.8.1 documentation
示例代码如下
%matplotlib auto
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig3 = plt.figure(constrained_layout=False)
gs1 = fig3.add_gridspec(nrows=3,ncols=3,left=0.05,right=0.48,wspace=0.05)
f3_ax1 = fig3.add_subplot(gs1[:-1,:])
f3_ax2 = fig3.add_subplot(gs1[-1,:-1])
f3_ax3 = fig3.add_subplot(gs1[-1,-1])
plt.show()
运行结果如图所示