课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
20分钟

使用 GridSpec 和 SubplotSpec

  1. 你可以直接创建matplotlib.gridspec.GridSpec然后通过它来创建SubPlot。如:
gs=matplotlib.gridspec.GridSpec(2,2) #网格2行2列  
matplotlib.pyplot.subplot(gs[0,0])

等价于matplotlib.pyplot.subplot2grid((2,2),(0,0))

2. GridSpec对对象提供了类似array的索引方法,其索引的结果是一个SubplotSpec对象实例。如果你想创建横跨多个网格的SubplotSpec,那么你需要对GridSpec对象执行分片索引,如pyplot.subplot(gs[0,:-1])

3. 如果你使用GridSpec,那么你可以调整由GridSpec创建的SubplotSpeclayout parameter。如:

gs=gridspec.GridSpec(3,3)  
gs.update(left=0.05,right=0.48,wspace=0.05)

这种用法类似于subplots_adjust,但是它仅仅影响由本GridSpec创建的SubplotSpec。其中gs.update()的关键字参数有:

  • left关键字参数:subplot左侧宽度
  • right关键字参数:subplot右侧宽度
  • bottom关键字参数:subplot底部高度
  • top关键字参数:subplot顶部高度
  • wspace关键字参数:subplot之间的空白宽度
  • hspace关键字参数:subplot之间的空白的高度

4. 你可以从SubplotSpec创建GridSpec。此时layout parameter由该SubplotSpec指定。如:

gs0=gridspec.GridSpec(1,2)
  gs00=gridspec.GridSpecFromSubplotSpec(3,3,subplot_spec=gs0[0])
  matplotlib.gridspec.GridSpecFromSubplotSpec(nrows, ncols, subplot_spec,
  wspace=None, hspace=None,height_ratios=None,width_ratios=None)

创建一个GridSpec,它的subplot layout parameter继承自指定的SubplotSpec。 其中nrows为网格行数,ncols为网格列数,subplot_spec为指定的SubplotSpec

5. 默认情况下,GridSpec创建的网格都是相同大小的。当然你可以调整相对的高度和宽度。注意这里只有相对大小(即比例)是有意义的,绝对大小值是没有意义的。如:  

gs=gridspec.GridSpec(2,2,width_ratios=[1,2],height_ratios=[4,1]
plt.subplot(gs[0]  ....

这里width_ratios关键字参数指定了一行中,各列的宽度比例(有多少列就有多少个数字); height_ratios关键字参数指定了一列中,各行的高度比例(有多少行就有多少个数字)。

  1. GridSpec.tight_layout() GridSpec.tight_layout(fig, renderer=None, pad=1.08, h_pad=None, w_pad=None,rect=None): tight_layout能够自动调整subplot param从而使得subplot适应figure area。 它仅仅检查ticklabel、axis label、title等内容是否超出绘制区域。其参数为:
    • fig关键字参数:Figure对象,图表。
    • pad关键字参数:一个浮点数,单位是fontsize,表示figure edgeedges of subplots之间的 填充区域。
    • h_pad关键字参数:一个浮点数,单位是fontsize,示subplots之间的高度,默认为pad
    • w_pad关键字参数:一个浮点数,单位是fontsize,示subplots之间的宽度,默认为pad
    • rect关键字参数:如果给定了该参数为一个列表或元组(是一个矩形的四要素,分别代表左下角坐标,宽度,高度),则指定了网格的轮廓矩形,所有的subplots都位于该矩形中。其坐标系是figure coordinate,从[0...1],如果没有提供该参数,则默认为(0, 0, 1, 1)

    当然你可以使用matplotlib.pyplot.tight_layout()来达到同样的效果。