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
How to make two plots side-by-side using Python?
When creating data visualizations, you often need to display multiple plots side-by-side for comparison. Python's Matplotlib provides the subplot() method to divide a figure into multiple sections and place plots in specific positions.
Using plt.subplot() Method
The subplot(nrows, ncols, index) method splits a figure into a grid of nrows × ncols sections. The index parameter specifies which section to use for the current plot ?
from matplotlib import pyplot as plt
import numpy as np
# Create sample data
x_points = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
y1_points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 20])
y2_points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 5])
# First subplot (left side)
plt.subplot(1, 2, 1) # 1 row, 2 columns, position 1
plt.plot(x_points, y1_points, 'b-o')
plt.title("Linear Growth")
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Second subplot (right side)
plt.subplot(1, 2, 2) # 1 row, 2 columns, position 2
plt.plot(x_points, y2_points, 'r-s')
plt.title("Exponential Decay")
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Adjust layout and display
plt.tight_layout()
plt.show()
Using plt.subplots() Method
An alternative approach uses subplots() to create figure and axes objects simultaneously ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# First plot
ax1.plot(x, y1, 'g-', linewidth=2)
ax1.set_title('Sine Wave')
ax1.set_xlabel('X values')
ax1.set_ylabel('sin(x)')
ax1.grid(True)
# Second plot
ax2.plot(x, y2, 'm-', linewidth=2)
ax2.set_title('Cosine Wave')
ax2.set_xlabel('X values')
ax2.set_ylabel('cos(x)')
ax2.grid(True)
plt.tight_layout()
plt.show()
Comparison
| Method | Syntax | Best For |
|---|---|---|
plt.subplot() |
plt.subplot(rows, cols, index) |
Simple layouts, quick plotting |
plt.subplots() |
fig, axes = plt.subplots(rows, cols) |
Complex layouts, more control |
Key Points
Use
plt.tight_layout()to prevent overlapping labelsSubplot indices start from 1, not 0
The
figsizeparameter controls the overall figure sizeEach subplot can have independent styling and formatting
Conclusion
Use plt.subplot() for simple side-by-side plots or plt.subplots() for more complex layouts. Both methods allow effective comparison of multiple datasets in a single figure.
