Subplots components Matplotlib
- In Matplotlib, subplots are used to create multiple plots within the same figure.
- The `plt.subplots()` function is commonly used to create a grid of subplots, and it returns a figure and an array of subplot axes.
- key components and methods related to creating subplots in Matplotlib:
1. Creating
Subplots:
- `plt.subplots(nrows, ncols, ...)`: Creates
a grid of subplots.
fig, axes = plt.subplots(nrows=2, ncols=2,
figsize=(10, 8))
- `nrows` and `ncols`: The number of rows
and columns in the subplot grid.
- `figsize`: The size of the entire figure.
2. Accessing
Subplots:
- - Subplots are accessed using the `axes` array returned by `plt.subplots()`.
- You can access a specific subplot using array indexing.
ax1 = axes[0, 0] # Accessing the top-left subplot
3. Data Plotting
in Subplots:
- You can plot data on each subplot
individually using the methods available on the subplot axes.
ax1.plot(x1, y1)
ax2.scatter(x2, y2)
4. Title and
Labels for Subplots:
- You can add a title to the entire figure
and individual titles to each subplot.
fig.suptitle('Main Title')
ax1.set_title('Subplot 1 Title')
- Axis labels are set similarly:
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
5. Sharing Axes:
- You can share the x or y axes between
subplots.
plt.subplots(nrows=2, ncols=2,
sharex=True, sharey=True)
6. Adjusting
Layout:
- `plt.tight_layout()`: Automatically
adjusts the subplot parameters to fit the figure area.
plt.tight_layout()
7. Saving and
Displaying the Plot:
- Save (`plt.savefig()`): Saves the plot to
a file.
- Show (`plt.show()`): Displays the plot on
the screen.
plt.show()
example:- creating
subplots in Matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0,
2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# Create subplots
fig, axes =
plt.subplots(nrows=3, ncols=1, figsize=(8, 12))
# Plot on each subplot
axes[0].plot(x,
y1, label='sin(x)', color='blue')
axes[0].set_title('Sine
Function')
axes[1].plot(x, y2, label='cos(x)', color='green')
axes[1].set_title('Cosine
Function')
axes[2].plot(x, y3, label='tan(x)', color='red')
axes[2].set_title('Tangent
Function')
# Add a common x-axis label
axes[-1].set_xlabel('x')
# Adjust layout for better spacing
plt.tight_layout()
# Show the plot
plt.show()
-------------------------------------------------------------------------------------------
0 Comments