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
Adjusting the heights of individual subplots in Matplotlib in Python
Matplotlib is a powerful Python library for creating graphs and plots. When working with multiple subplots, you often need to adjust their individual heights to better display your data. This article demonstrates how to control subplot heights using two effective methods.
Understanding Subplots
A subplot is a smaller plot within a larger figure. You can arrange multiple subplots in rows and columns to compare different datasets or show related visualizations together.
Method 1: Using gridspec_kw Parameter
The gridspec_kw parameter in plt.subplots() allows you to specify height ratios directly when creating subplots ?
Syntax
fig, (ax1, ax2) = plt.subplots(
2, 1, # 2 rows, 1 column
gridspec_kw={'height_ratios': [3, 1]} # First subplot 3x taller
)
Example
import matplotlib.pyplot as plt
import numpy as np
# Create figure with custom height ratios
fig, (ax1, ax2) = plt.subplots(
2, 1,
figsize=(8, 6),
gridspec_kw={'height_ratios': [3, 1]}
)
# Plot data in the larger subplot
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
ax1.plot(x, y1, 'b-', linewidth=2)
ax1.set_title("Main Plot (3x height)")
ax1.set_ylabel("Amplitude")
ax1.grid(True)
# Plot data in the smaller subplot
y2 = np.cos(x)
ax2.plot(x, y2, 'r-', linewidth=2)
ax2.set_title("Secondary Plot (1x height)")
ax2.set_xlabel("X values")
ax2.set_ylabel("Amplitude")
ax2.grid(True)
plt.tight_layout()
plt.show()
Method 2: Using GridSpec Class
The GridSpec class provides more control over subplot layouts, especially for complex arrangements ?
Syntax
from matplotlib import gridspec fig = plt.figure(figsize=(8, 6)) gs = gridspec.GridSpec(3, 1, height_ratios=[2, 1, 1]) ax1 = fig.add_subplot(gs[0]) ax2 = fig.add_subplot(gs[1]) ax3 = fig.add_subplot(gs[2])
Example
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
# Create figure
fig = plt.figure(figsize=(10, 8))
# Define grid with custom height ratios
gs = gridspec.GridSpec(3, 1, height_ratios=[3, 1, 2], hspace=0.3)
# Create subplots
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
ax3 = fig.add_subplot(gs[2])
# Sample data
x = np.linspace(0, 2*np.pi, 100)
# Plot in first subplot (largest)
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.plot(x, np.cos(x), 'r-', label='cos(x)')
ax1.set_title("Trigonometric Functions (Height ratio: 3)")
ax1.legend()
ax1.grid(True)
# Plot in second subplot (smallest)
ax2.plot(x, np.sin(x) * np.cos(x), 'g-')
ax2.set_title("sin(x) × cos(x) (Height ratio: 1)")
ax2.grid(True)
# Plot in third subplot (medium)
ax3.plot(x, x**2, 'm-')
ax3.set_title("Quadratic Function (Height ratio: 2)")
ax3.set_xlabel("X values")
ax3.grid(True)
plt.show()
Comparison
| Method | Best For | Flexibility | Code Complexity |
|---|---|---|---|
gridspec_kw |
Simple layouts | Basic | Low |
GridSpec |
Complex layouts | High | Medium |
Key Points
- Height ratios are relative values −
[3, 1]means the first subplot is 3 times taller - Use
plt.tight_layout()to automatically adjust spacing - The
hspaceparameter inGridSpeccontrols vertical spacing between subplots - Both methods work with any number of rows and columns
Conclusion
Use gridspec_kw for simple subplot arrangements with custom heights. Choose GridSpec when you need more control over complex layouts. Both methods provide effective ways to create visually balanced subplot arrangements in matplotlib.
