# 使用 GridSpec 自定義子圖位置
> 原文:[Customizing Location of Subplot Using GridSpec](http://matplotlib.org/users/gridspec.html)
> 譯者:[飛龍](https://github.com/)
> 協議:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
`GridSpec`
指定子圖將放置的網格的幾何位置。 需要設置網格的行數和列數。 子圖布局參數(例如,左,右等)可以選擇性調整。
`SubplotSpec`
指定在給定`GridSpec`中的子圖位置。
`subplot2grid`
一個輔助函數,類似于`pyplot.subplot`,但是使用基于 0 的索引,并可使子圖跨越多個格子。
## `subplot2grid`基本示例
要使用subplot2grid,你需要提供網格的幾何形狀和網格中子圖的位置。 對于簡單的單網格子圖:
```py
ax = plt.subplot2grid((2,2),(0, 0))
```
等價于:
```
ax = plt.subplot(2,2,1)
```
```
nRow=2, nCol=2
(0,0) +-------+-------+
| 1 | |
+-------+-------+
| | |
+-------+-------+
```
要注意不想`subplot`,`gridspec`中的下標從 0 開始。
為了創建跨越多個格子的子圖,
```py
ax2 = plt.subplot2grid((3,3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
```
例如,下列命令:
```py
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))
```
會創建:

## `GridSpec`和`SubplotSpec`
你可以顯式創建`GridSpec `并用它們創建子圖。
例如,
```py
ax = plt.subplot2grid((2,2),(0, 0))
```
等價于:
```py
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
```
`gridspec `示例提供類似數組(一維或二維)的索引,并返回`SubplotSpec`實例。例如,使用切片來返回跨越多個格子的`SubplotSpec`實例。
上面的例子會變成:
```py
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1,:-1])
ax3 = plt.subplot(gs[1:, -1])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])
```

## 調整 `GridSpec`布局
在顯式使用`GridSpec`的時候,你可以調整子圖的布局參數,子圖由`gridspec`創建。
```py
gs1 = gridspec.GridSpec(3, 3)
gs1.update(left=0.05, right=0.48, wspace=0.05)
```
這類似于`subplots_adjust`,但是他只影響從給定`GridSpec`創建的子圖。
下面的代碼
```py
gs1 = gridspec.GridSpec(3, 3)
gs1.update(left=0.05, right=0.48, wspace=0.05)
ax1 = plt.subplot(gs1[:-1, :])
ax2 = plt.subplot(gs1[-1, :-1])
ax3 = plt.subplot(gs1[-1, -1])
gs2 = gridspec.GridSpec(3, 3)
gs2.update(left=0.55, right=0.98, hspace=0.05)
ax4 = plt.subplot(gs2[:, :-1])
ax5 = plt.subplot(gs2[:-1, -1])
ax6 = plt.subplot(gs2[-1, -1])
```
會產生

## 使用 `SubplotSpec`創建 `GridSpec`
你可以從`SubplotSpec`創建`GridSpec`,其中它的布局參數設置為給定`SubplotSpec`的位置的布局參數。
```py
gs0 = gridspec.GridSpec(1, 2)
gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0])
gs01 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[1])
```

## 使用`SubplotSpec`創建復雜嵌套的`GridSpec`
這里有一個更復雜的嵌套`gridspec`的示例,我們通過在每個 3x3 內部網格中隱藏適當的脊線,在 4x4 外部網格的每個單元格周圍放置一個框。

## 網格尺寸可變的`GridSpec`
通常,`GridSpec`創建大小相等的網格。你可以調整行和列的相對高度和寬度,要注意絕對高度值是無意義的,有意義的只是它們的相對比值。
```py
gs = gridspec.GridSpec(2, 2,
width_ratios=[1,2],
height_ratios=[4,1]
)
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])
```
