Matplotlib Subplots
We can use the **subplot()** and **subplots()** methods in pyplot to draw multiple subplots.
The **subplot()** method requires specifying the position when plotting, while the **subplots()** method can generate multiple subplots at once. When calling it, you only need to use the `ax` attribute of the generated object.
### subplot
subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(**kwargs) subplot(ax)
The above functions divide the entire plotting area into `nrows` rows and `ncols` columns, then number each sub-area from 1 to N in order from left to right, top to bottom. The top-left sub-area is numbered 1, and the bottom-right is numbered N. The numbering can be set via the **index** parameter.
Setting `numRows = 1` and `numCols = 2` means plotting in a 1x2 image area. The corresponding coordinates are:
(1, 1), (1, 2)
**plotNum = 1** corresponds to the coordinate (1, 1), which is the subplot in the first row and first column.
**plotNum = 2** corresponds to the coordinate (1, 2), which is the subplot in the first row and second column.
## Example
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
xpoints = np.array([0,6])
ypoints = np.array([0,100])
plt.subplot(1,2,1)
plt.plot(xpoints,ypoints)
plt.title("plot 1")
#plot 2:
x = np.array([1,2,3,4])
y = np.array([1,4,9,16])
plt.subplot(1,2,2)
plt.plot(x,y)
plt.title("plot 2")
plt.suptitle(" subplot Test")
plt.show()
The result is shown below:
!(#)
Setting `numRows = 2` and `numCols = 2` means plotting in a 2x2 image area. The corresponding coordinates are:
(1, 1), (1, 2)(2, 1), (2, 2)
**plotNum = 1** corresponds to the coordinate (1, 1), which is the subplot in the first row and first column.
**plotNum = 2** corresponds to the coordinate (1, 2), which is the subplot in the first row and second column.
**plotNum = 3** corresponds to the coordinate (2, 1), which is the subplot in the second row and first column.
**plotNum = 4** corresponds to the coordinate (2, 2), which is the subplot in the second row and second column.
## Example
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0,6])
y = np.array([0,100])
plt.subplot(2,2,1)
plt.plot(x,y)
plt.title("plot 1")
#plot 2:
x = np.array([1,2,3,4])
y = np.array([1,4,9,16])
plt.subplot(2,2,2)
plt.plot(x,y)
plt.title("plot 2")
#plot 3:
x = np.array([1,2,3,4])
y = np.array([3,5,7,9])
plt.subplot(2,2,3)
plt.plot(x,y)
plt.title("plot 3")
#plot 4:
x = np.array([1,2,3,4])
y = np.array([4,5,6,7])
plt.subplot(2,2,4)
plt.plot(x,y)
plt.title("plot 4")
plt.suptitle(" subplot Test")
plt.show()
The result is shown below:
!(#)
### subplots()
The syntax for the subplots() method is as follows:
matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
**Parameter Description:**
* **nrows**: Default is 1, sets the number of rows in the chart.
* **ncols**: Default is 1, sets the number of columns in the chart.
* **sharex, sharey**: Sets whether the x and y axes share attributes. Default is false, can be set to 'none', 'all', 'row', or 'col'. False or 'none' means each subplot's x or y axis is independent. True or 'all' means all subplots share the x or y axis. 'row' sets each subplot row to share one x or y axis. 'col' sets each subplot column to share one x or y axis.
* **squeeze**: Boolean, default is True. Indicates that extra dimensions are squeezed out from the returned Axes object. For N*1 or 1*N subplots, returns a 1D array. For N*M, where N>1 and M>1, returns a 2D array. If set to False, no squeezing is performed, and a 2D array of Axes instances is returned, even if it is ultimately 1x1.
* **subplot_kw**: Optional, dictionary type. Passes the dictionary keywords to add_subplot() to create each subplot.
* **gridspec_kw**: Optional, dictionary type. Passes the dictionary keywords to the GridSpec constructor to place subplots in a grid.
* ****fig_kw**: Passes detailed keyword arguments to the figure() function.
## Example
import matplotlib.pyplot as plt
import numpy as np
# Create some test data -- Figure 1
x = np.linspace(0,2*np.pi,400)
y = np.sin(x**2)
# Create a figure and subplot -- Figure 2
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots -- Figure 3
f,(ax1, ax2)= plt.subplots(1,2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four subplots -- Figure 4
fig, axs = plt.subplots(2,2, subplot_kw=dict(projection="polar"))
axs[0,0].plot(x, y)
axs[1,1].scatter(x, y)
# Share x axis
plt.subplots(2,2, sharex='col')
# Share y axis
plt.subplots(2,2, sharey='row')
# Share x and y axes
plt.subplots(2,2, sharex='all', sharey='all')
# This also shares x and y axes
plt.subplots(2,2, sharex=True, sharey=True)
# Create a figure with label 10, delete if it already exists
fig, ax = plt.subplots(num=10, clear=True)
plt.show()
Some of the chart results are shown below:
**Figure 1**
!(#)
**Figure 2**
!(#)
**Figure 3**
!(#)
**Figure 4**
!(#)
YouTip