Python:Matplotlib .subplot()
The .subplot() function in Matplotlib creates a subplot within a figure based on a specified grid layout or returns an existing subplot if one already occupies the given position. It offers a straightforward way to incrementally build and modify figures, making it useful for creating flexible and customizable multi-plot layouts.
Typical use cases for .subplot() include incrementally constructing figures with multiple plots, dynamically adding or updating subplots, and fine-tuning individual plots within a figure during exploratory data analysis, or interactive visualization.
Syntax
matplotlib.pyplot.subplot(*args, **kwargs)
Parameters:
*args: Defines the subplot position. It can be specified in two ways:- Three integers:
(nrows, ncols, index)— defines the number of rows, columns, and the position of the subplot. - A single integer: For example,
plt.subplot(221)is equivalent toplt.subplot(2, 2, 1).
- Three integers:
**kwargs: Additional keyword arguments for subplot customization, such as:projection: Sets the projection type ('rectilinear','polar','3d', etc.).polar: IfTrue, creates a polar projection subplot.sharex,sharey: Share the x-axis or y-axis with another subplot.label: Internal label used to identify the returnedAxesobject.- Any other valid
Axesproperties.
Return value:
Returns an Axes object representing the subplot. This object can be used to modify, label, or further customize the subplot.
Example 1: Basic Subplot Creation using .subplot()
This example demonstrates the fundamental usage of .subplot() to create a simple 1x2 grid of plots:
import matplotlib.pyplot as pltimport numpy as np# Create sample datax = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x)# Create first subplot (1 row, 2 columns, first position - using triple)plt.subplot(1, 2, 1)plt.plot(x, y1, 'b-', linewidth=2)plt.title('Sine Wave')plt.xlabel('x')plt.ylabel('sin(x)')plt.grid(True)# Create second subplot (1 row, 2 columns, second position - using single integer)plt.subplot(122)plt.plot(x, y2, 'r-', linewidth=2)plt.title('Cosine Wave')plt.xlabel('x')plt.ylabel('cos(x)')plt.grid(True)# Adjust layout and displayplt.tight_layout()plt.show()
The output generated by this code will be:

This example creates two side-by-side plots showing sine and cosine waves. The .subplot() function allows us to create the plots one-by-one. Each subplot can be customized independently using its returned Axes object.
Example 2: Non-Uniform Plot for Sales Data Comparison Dashboard
This example shows how to use .subplot() to create a business dashboard comparing quarterly sales data across different metrics:
import matplotlib.pyplot as plt# Sample quarterly sales dataquarters = ['Q1', 'Q2', 'Q3', 'Q4']revenue = [125000, 150000, 175000, 200000]units_sold = [1250, 1400, 1600, 1800]profit_margin = [0.15, 0.18, 0.22, 0.25]# We want 2 rows, with 1 big plot in the first row and 3 small plots in the second row# 1st Row: Revenue Bar Chartax1 = plt.subplot(2, 1, 1)ax1.bar(quarters, revenue, color='skyblue', alpha=0.7)ax1.set_title('Quarterly Revenue')ax1.set_ylabel('Revenue ($)')ax1.tick_params(axis='y', labelcolor='blue')# 2nd Row, 1st Column: Units Sold Line Chartax2 = plt.subplot(2, 3, 4)ax2.plot(quarters, units_sold, marker='o', color='green', linewidth=3)ax2.set_title('Units Sold per Quarter')ax2.set_ylabel('Units')ax2.grid(True, alpha=0.3)# 2nd Row, 2nd Column: Profit margin trendax3 = plt.subplot(2, 3, 5)ax3.plot(quarters, profit_margin, marker='s', color='red', linewidth=2)ax3.set_title('Profit Margin Trend')ax3.set_ylabel('Profit Margin')ax3.set_ylim(0, 0.3)ax3.grid(True, alpha=0.3)# 2nd Row, 3rd Column: Combined revenue vs unitsax4 = plt.subplot(2, 3, 6)ax4_twin = ax4.twinx()bars = ax4.bar(quarters, revenue, alpha=0.6, color='lightblue', label='Revenue')line = ax4_twin.plot(quarters, units_sold, 'ro-', label='Units')ax4.set_title('Revenue vs Units Sold')ax4.set_ylabel('Revenue ($)', color='blue')ax4_twin.set_ylabel('Units Sold', color='red')# Adjust layout to prevent overlapplt.tight_layout()plt.show()
The output generated by this code will be:

This example demonstrates a real-world business scenario where multiple related metrics need to be visualized together. The custom grid layout allows for greater emphasis on overall revenue, with smaller plots for other supporting metrics.
Example 3: Dynamic Plotting for Genetic Data
This example illustrates using .subplot() for dynamic plotting, where number of subplots may vary based on the data:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd# Expression levels of 5 genes across 8 samplesnp.random.seed(0)data = pd.DataFrame({f'Gene_{i}': np.random.normal(loc=i*2, scale=np.random.uniform(0.3, 2), size=8)for i in range(1, 6)})# Threshold for "interesting" variationthreshold = 1.0interesting_genes = [gene for gene in data.columns if data[gene].std() > threshold]# Dynamically create subplots only for those genesfor i, gene in enumerate(interesting_genes, start=1):plt.subplot(len(interesting_genes), 1, i) # dynamic positioningplt.plot(data[gene], marker='o')plt.title(f"{gene} (std={data[gene].std():.2f})")plt.ylabel("Expression")plt.grid(alpha=0.3)plt.tight_layout()plt.show()
The output generated by this code will be:

This scientific example showcases how .subplot() can be used to create varying number of plots based on genes in the data which meet a particular threshold of variance. This approach is handy when exploring a new dataset.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Matplotlib on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours