GridSpec是matplotlib库中的一个类,用于创建规则的子图布局。它允许用户在一个图中创建不同大小和比例的子图,并指定它们的位置和间距。通过GridSpec,可以在一个图中实现复杂的子图布局,同时保持子图之间的一致性。
一、使用GridSpec()方法创建子图的布局结构
1. 导入必要的库和模块。
%matplotlib auto
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
2. 创建一个Figure实例,表示绘图的整个窗口或页面
fig = plt.figure()
3. 3.创建“区域规划图”实例(GridSpec实例)
spec = gridspec.GridSpec(nrows=2,
ncols=2,
figure=fig,
#hspace=2, #坐标系实例之间纵向间距
#wspace=2, #坐标系实例之间横向间距
#left=0.25,right=0.9,top=0.9,bottom=0.25, #把所有坐标实例打包在一起,整体伸缩/平移
width_ratios=[3,1], #设置坐标系的相对宽度(每个坐标系宽度=设定值/sum(设定值))
height_ratios=[3,1] #设置坐标系的相对高度(每个坐标系宽度=设定值/sum(设定值))
)
width_ratios 设置坐标系的相对宽度(每个坐标系宽度=设定值/sum(设定值))
height_ratios 设置坐标系的相对高度(每个坐标系宽度=设定值/sum(设定值))
4.根据给定的"区域规划图",创建对应的坐标系实例
ax1 = fig.add_subplot(spec[0,0]) # 二维数组的索引操作
ax2 = fig.add_subplot(spec[0,1]) #二维数组索引操作
ax3 = fig.add_subplot(spec[1,0])
ax4 = fig.add_subplot(spec[1,1])
5.最后显示效果
plt.show()
运行结果:
二、添加 left,right,top,bottom
left,right,top,bottom 把所有坐标实例打包在一起,整体伸缩/平移
spec = gridspec.GridSpec(nrows=2,
ncols=2,
figure=fig,
hspace=2, #坐标系实例之间纵向间距
wspace=2, #坐标系实例之间横向间距
left=0.25,right=0.9,top=0.9,bottom=0.25, #把所有坐标实例打包在一起,整体伸缩/平移
width_ratios=[3,1], #设置坐标系的相对宽度(每个坐标系宽度=设定值/sum(设定值))
height_ratios=[3,1] #设置坐标系的相对高度(每个坐标系宽度=设定值/sum(设定值))
)
展示图表:
plt.show()
运行成果:
三、使用add_gridspec0方法向画布添加布局结构
1.导入模块
%matplotlib auto
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
2.创建画布实例
fig = plt.figure()
3.创建“区域规划图”实例(GridSpec实例)
spec = gridspec.GridSpec(nrows=2,
ncols=2,
figure=fig,
hspace=2, #坐标系实例之间纵向间距
wspace=2, #坐标系实例之间横向间距
left=0.25,right=0.9,top=0.9,bottom=0.25, #把所有坐标实例打包在一起,整体伸缩/平移
width_ratios=[3,1], #设置坐标系的相对宽度(每个坐标系宽度=设定值/sum(设定值))
height_ratios=[3,1] #设置坐标系的相对高度(每个坐标系宽度=设定值/sum(设定值))
)
4.根据给定的"区域规划图",创建对应的坐标系实例
gs = fig.add_gridspec(3,3)
ax1 = fig.add_subplot(gs[0,:])
ax1.set_title('gs[0, :]')
ax2 = fig.add_subplot(gs[1,:-1])
ax2.set_title('gs[1, :-1]')
ax3 = fig.add_subplot(gs[1:,-1])
ax3.set_title('gs[1:,-1]')
ax4 = fig.add_subplot(gs[-1,0])
ax4.set_title('gs[-1,0]')
ax5 = fig.add_subplot(gs[-1,-2])
ax5.set_title('gs[-1,-2]')
5.展示图表
plt.tight_layout()
plt.show()
运行结果:
通过以上步骤,可以实现一个具有指定布局的子图网格,并在每个子图中进行相应的绘图操作。这样的布局可以用于展示多个相关图形,并在一个图中进行比较和分析。GridSpec提供了灵活的布局控制,使用户可以根据需要创建各种复杂的子图布局。