目录
plt.subplot2grid函数
plt.subplot2grid 是 Matplotlib 库中用于创建基于网格布局的子图的函数。它允许我们在网格中指定子图的位置和大小。其基本用法如下:
plt.subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
其中:
- (nrows, ncols) 指定了网格的行数和列数。
- (row, col) 指定了子图的起始位置。
- rowspan 和 colspan分别指定了子图所占的行数和列数。
method 1:subplot2grid
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 1:subplot2grid
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),colspan =3,rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')
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),colspan =1,rowspan=1)
ax5=plt.subplot2grid((3,3),(2,1),colspan =1,rowspan=1)
plt.tight_layout()
plt.show()
gridspec.GridSpec函数
gridspec.GridSpec 是 Matplotlib 库中用于创建复杂网格布局的函数。它允许我们更灵活地指定子图的位置和大小,以及子图之间的间距。
method 2:gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 2:gridspec
plt.figure()
gs =gridspec.GridSpec(3,3)
ax1=plt.subplot(gs[0,:])
ax1=plt.subplot(gs[1,:2])
ax1=plt.subplot(gs[1:,2])
ax1=plt.subplot(gs[-1,0])
ax1=plt.subplot(gs[-1,-2])
plt.tight_layout()
plt.show()
method3:easy to define structure
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method3:easy to define structure
f,((ax11,ax12),(ax21,ax22)) =plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])
ax12.scatter([1.5,2],[1,2])
ax21.scatter([0.5,2],[1,2])
ax22.scatter([1.3,1.8],[1,2])
plt.show()