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 several plots on a single page using matplotlib in Python?
Matplotlib provides several methods to create multiple plots on a single page. You can use subplots() to create a grid of subplots or subplot() to add plots one by one. This is useful for comparing different datasets or showing related visualizations together.
Method 1: Using subplots() with Multiple Axes
The subplots() function creates a figure with multiple subplot areas in a grid layout −
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.log(x + 1)
# Create 2x2 grid of subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Plot on each subplot
axes[0, 0].plot(x, y1, 'b-')
axes[0, 0].set_title('Sine Wave')
axes[0, 0].set_xlabel('X')
axes[0, 0].set_ylabel('sin(x)')
axes[0, 1].plot(x, y2, 'r-')
axes[0, 1].set_title('Cosine Wave')
axes[0, 1].set_xlabel('X')
axes[0, 1].set_ylabel('cos(x)')
axes[1, 0].plot(x, y3, 'g-')
axes[1, 0].set_title('Tangent Wave')
axes[1, 0].set_xlabel('X')
axes[1, 0].set_ylabel('tan(x)')
axes[1, 0].set_ylim(-5, 5) # Limit y-axis for better view
axes[1, 1].plot(x, y4, 'm-')
axes[1, 1].set_title('Logarithmic Function')
axes[1, 1].set_xlabel('X')
axes[1, 1].set_ylabel('log(x+1)')
# Adjust spacing between subplots
plt.tight_layout()
plt.show()
Method 2: Using subplot() Function
The subplot() function adds subplots one at a time using a three-digit code (rows, columns, position) −
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.arange(1, 11)
y1 = x**2
y2 = x**3
y3 = np.sqrt(x)
# Create figure
plt.figure(figsize=(12, 4))
# First subplot (1 row, 3 columns, position 1)
plt.subplot(1, 3, 1)
plt.plot(x, y1, 'bo-')
plt.title('Quadratic Function')
plt.xlabel('X')
plt.ylabel('X²')
# Second subplot (1 row, 3 columns, position 2)
plt.subplot(1, 3, 2)
plt.plot(x, y2, 'rs-')
plt.title('Cubic Function')
plt.xlabel('X')
plt.ylabel('X³')
# Third subplot (1 row, 3 columns, position 3)
plt.subplot(1, 3, 3)
plt.plot(x, y3, 'g^-')
plt.title('Square Root Function')
plt.xlabel('X')
plt.ylabel('?X')
plt.tight_layout()
plt.show()
Method 3: Mixing Different Plot Types
You can combine different types of plots like scatter, bar, and line plots on the same page −
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Sample data
students = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
math_scores = [85, 92, 78, 96, 89]
science_scores = [90, 88, 85, 94, 91]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [120, 135, 98, 156, 142]
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Scatter plot
axes[0, 0].scatter(math_scores, science_scores, c=['red', 'blue', 'green', 'orange', 'purple'], s=100)
axes[0, 0].set_title('Math vs Science Scores')
axes[0, 0].set_xlabel('Math Scores')
axes[0, 0].set_ylabel('Science Scores')
# Bar plot
axes[0, 1].bar(students, math_scores, color='lightblue')
axes[0, 1].set_title('Math Scores by Student')
axes[0, 1].set_xlabel('Students')
axes[0, 1].set_ylabel('Math Scores')
axes[0, 1].tick_params(axis='x', rotation=45)
# Line plot
axes[1, 0].plot(months, sales, 'o-', color='green', linewidth=2, markersize=8)
axes[1, 0].set_title('Monthly Sales Trend')
axes[1, 0].set_xlabel('Months')
axes[1, 0].set_ylabel('Sales')
# Pie chart
axes[1, 1].pie(math_scores, labels=students, autopct='%1.1f%%', startangle=90)
axes[1, 1].set_title('Math Scores Distribution')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
nrows, ncols |
Number of rows and columns in the grid | plt.subplots(2, 3) |
figsize |
Figure size in inches (width, height) | figsize=(10, 8) |
tight_layout() |
Automatically adjusts spacing between subplots | plt.tight_layout() |
sharex, sharey |
Share x or y axes between subplots | sharex=True |
Conclusion
Use subplots() to create multiple plots in a grid layout for comparing related data. The tight_layout() function automatically adjusts spacing for better presentation. Multiple plots on a single page help visualize relationships and patterns across different datasets effectively.
