Python:Matplotlib .subplot()

Musab1Blaser's avatar
Published Oct 31, 2025
Contribute to Docs

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.

  • 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

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 to plt.subplot(2, 2, 1).
  • **kwargs: Additional keyword arguments for subplot customization, such as:
    • projection: Sets the projection type ('rectilinear', 'polar', '3d', etc.).
    • polar: If True, creates a polar projection subplot.
    • sharex, sharey: Share the x-axis or y-axis with another subplot.
    • label: Internal label used to identify the returned Axes object.
    • Any other valid Axes properties.

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 plt
import numpy as np
# Create sample data
x = 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 display
plt.tight_layout()
plt.show()

The output generated by this code will be:

Side-by-side line plots of sine and cosine waves with labelled axes and grid lines

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 data
quarters = ['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 Chart
ax1 = 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 Chart
ax2 = 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 trend
ax3 = 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 units
ax4 = 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 overlap
plt.tight_layout()
plt.show()

The output generated by this code will be:

A custom grid layout showing revenue, units sold, profit margin, and a combined revenue-units chart for quarterly sales data

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 plt
import numpy as np
import pandas as pd
# Expression levels of 5 genes across 8 samples
np.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" variation
threshold = 1.0
interesting_genes = [gene for gene in data.columns if data[gene].std() > threshold]
# Dynamically create subplots only for those genes
for i, gene in enumerate(interesting_genes, start=1):
plt.subplot(len(interesting_genes), 1, i) # dynamic positioning
plt.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:

A dynamically sized grid of line plots for genes with high variance

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.

All contributors

Contribute to 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