Grid Manager¶
matplotlib.pyplot.subplot¶
Manual Plotting¶
In [271]:
fig = plt.figure()
fig.add_axes([0,0,1,1])
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],
xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],
ylim=(-1.2, 1.2))
In [272]:
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],
xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],
ylim=(-1.2, 1.2))
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x));
In [273]:
ax1 = plt.axes() # standard axes ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

Create Subplot Individually¶
Each call lto subplot() will create a new container for subsequent plot command
In [274]:
plt.subplot(2,4,1) plt.text(0.5, 0.5, 'one',fontsize=18, ha='center') plt.subplot(2,4,8) plt.text(0.5, 0.5, 'eight',fontsize=18, ha='center')
Out[274]:
Text(0.5,0.5,'eight')
In [275]:
for i in range(1, 7):
plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')

Create Subplots Upfront¶
subplots() returns two variables:
- fig : reference to the entire container
- ax : reference to individual plot. It is an array
In [276]:
fig, ax = plt.subplots(2, 3) # individual axes
In [277]:
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row') # removed inner label

Iterate through subplots (ax) to populate them
In [278]:
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)),
fontsize=18, ha='center')

Complicated Arrangement¶
In [279]:
plt.figure(figsize=(5,5)) grid = plt.GridSpec(2, 3, hspace=0.4, wspace=0.4) plt.subplot(grid[0, 0]) #row 0, col 0 plt.subplot(grid[0, 1:]) #row 0, col 1 to : plt.subplot(grid[1, :2]) #row 1, col 0:2 plt.subplot(grid[1, 2]) #ro2 1, col 2
Out[279]:
<matplotlib.axes._subplots.AxesSubplot at 0x2c31a70f5f8>
In [280]:
plt.figure(figsize=(5,5)) grid = plt.GridSpec(4, 4, hspace=0.4, wspace=0.4) plt.subplot(grid[:3, 0]) # row 0:3, col 0 plt.subplot(grid[:3, 1: ]) # row 0:3, col 1: plt.subplot(grid[3, 1: ]); # row 3, col 1:

-1 means last row or column
In [281]:
plt.figure(figsize=(6,6)) grid = plt.GridSpec(4, 4, hspace=0.4, wspace=1.2) plt.subplot(grid[:-1, 0 ]) # row 0 till last row (not including last row), col 0 plt.subplot(grid[:-1, 1:]) # row 0 till last row (not including last row), col 1 till end plt.subplot(grid[-1, 1: ]); # row last row, col 1 till end
