Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to combine several matplotlib axes subplots into one figure?
To combine several matplotlib axes subplots into one figure, we can use subplots() method with nrows parameter to create multiple subplot arrangements in a single figure.
Steps
- Set the figure size and adjust the padding between and around the subplots
- Create x, y1 and y2 data points using numpy
- Create a figure and a set of subplots using subplots() method
- Plot x, y1 and y2 data points using plot() method
- To display the figure, use show() method
Example − Vertical Subplots
Here's how to create two subplots arranged vertically ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(nrows=2)
line1, = axes[0].plot(x, y1, color='red')
line2, = axes[1].plot(x, y2, color='green')
axes[0].set_title('Sine Wave')
axes[1].set_title('Cosine Wave')
plt.show()
Example − Horizontal Subplots
You can also arrange subplots horizontally using ncols parameter ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(ncols=2)
axes[0].plot(x, y1, color='red')
axes[1].plot(x, y2, color='green')
axes[0].set_title('Sine Wave')
axes[1].set_title('Cosine Wave')
plt.show()
Example − Grid Layout
For more complex layouts, you can create a grid of subplots ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [10, 8]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = x**2
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 0].plot(x, y1, color='red')
axes[0, 0].set_title('Sine')
axes[0, 1].plot(x, y2, color='green')
axes[0, 1].set_title('Cosine')
axes[1, 0].plot(x, y3, color='blue')
axes[1, 0].set_title('Tangent')
axes[1, 0].set_ylim(-5, 5)
axes[1, 1].plot(x, y4, color='orange')
axes[1, 1].set_title('Quadratic')
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
nrows |
Number of rows | nrows=2 |
ncols |
Number of columns | ncols=3 |
figsize |
Figure dimensions | figsize=[8, 6] |
Conclusion
Use plt.subplots(nrows, ncols) to create multiple subplots in one figure. Access individual subplots using array indexing like axes[0] for single dimension or axes[row, col] for grids.
Advertisements
