Matplotlib Drawing Multiple Plots
We can use the subplot() and subplots() methods from pyplot to create multiple subplots.
The subplot() method requires specifying the position when plotting, while the subplots() method can generate multiple subplots at once, and you only need to call the ax of the generated object when invoking it.
subplot
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)
The above function divides the entire plotting area into nrows rows and ncols columns, then numbers each sub-region from left to right, top to bottom, starting from 1...N
, with the top-left sub-region numbered 1 and the bottom-right region numbered N. The numbering can be set via the index parameter.
Setting numRows = 1, numCols = 2, divides the chart into a 1x2 grid, with corresponding coordinates:
(1, 1), (1, 2)
plotNum = 1 represents the coordinates (1, 1), i.e., the subplot in the first row and first column.
plotNum = 2 represents the coordinates (1, 2), i.e., 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("tutorialpro subplot Test")
plt.show()
The display result is as follows:
Setting numRows = 2, numCols = 2, divides the chart into a 2x2 grid, with corresponding coordinates:
(1, 1), (1, 2)
(2, 1), (2, 2)
plotNum = 1 represents the coordinates (1, 1), i.e., the subplot in the first row and first column.
plotNum = 2 represents the coordinates (1, 2), i.e., the subplot in the first row and second column.
plotNum = 3 represents the coordinates (2, 1), i.e., the subplot in the second row and first column.
plotNum = 4 represents the coordinates (2, 2), i.e., 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("tutorialpro subplot Test")
plt.show()
The display result is as follows:
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)
- nrows: Defaults to 1, sets the number of rows in the figure.
- ncols: Defaults to 1, sets the number of columns in the figure.
- sharex, sharey: Sets whether x and y axes are shared. Defaults to False, can be set to 'none', 'all', 'row', or 'col'.
- False or none: Each subplot's x or y axis is independent.
- True or 'all': All subplots share the x or y axis.
- 'row': Each row of subplots shares an x or y axis.
- 'col': Each column of subplots shares an x or y axis.
- squeeze: Boolean, defaults to True, indicating that extra dimensions are squeezed out from the returned Axes object. For N1 or 1N subplots, a 1-dimensional array is returned. For N*M, N>1 and M>1, a 2-dimensional array is returned. If set to False, no squeezing is performed, and a 2-dimensional array of Axes instances is returned, even if it ends up being 1x1.
- subplotkw: Optional, dictionary type. Passes the dictionary keywords to addsubplot() to create each subplot.
- gridspec_kw: Optional, dictionary type. Passes the dictionary keywords to the GridSpec constructor to create 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 figure labeled 10, clear if already exists
fig, ax = plt.subplots(num=10, clear=True)
plt.show()
Some of the displayed results are as follows:
Figure 1
Figure 2
Figure 3
Figure 4