Matplotlib Subplot (Python Programming)
Learn Matplotlib Subplot (Python Programming) step by step with clear examples and exercises.
Title: Matplotlib Subplot (Python Programming)
Why This Matters
Matplotlib is an essential library for data analysis and visualization in Python, offering powerful tools to create high-quality plots. The subplot() function allows you to arrange multiple plots within a single figure, making it easier to compare and contrast different datasets. Mastering the use of subplots can significantly enhance your data visualization skills and make your work more efficient.
Prerequisites
- Basic understanding of Python programming
- Familiarity with Matplotlib library (you can refer to our Matplotlib tutorial if needed)
Before diving into the core concept, let's discuss some key terms:
- Axis: A graphical representation of a variable on a plot. There are two primary axes in Matplotlib: x-axis (horizontal) and y-axis (vertical).
- Figure: A container for multiple plots or subplots.
- Subplot: A smaller plot within a figure created using the
subplot()function.
Core Concept
The subplot() function is used to create multiple plots within a single figure. It takes several arguments, which are explained below:
nrowsandncols: These parameters specify the number of rows and columns in the grid where you want to place your subplots. For example,subplot(2, 2, 1)will create a 2x2 grid and select the top-left subplot (index 1).
figsize: This parameter allows you to specify the size of the figure in inches. For example,subplot(2, 2, 1, figsize=(8,6))will create a figure of size 8x6 inches.
sharexandsharey: These parameters are used when you want to share the x-axis or y-axis across multiple subplots. Settingsharex=True(orsharey=True) ensures that the same x-axis (or y-axis) is used for all subplots in a row (or column).
Here's an example of creating a 2x2 grid with shared x-axis and separate y-axes:
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2, figsize=(8,6), sharex='all')
Create data for the subplots
data1 = np.random.normal(0, 1, 50)
data2 = np.random.normal(1, 1, 50)
data3 = np.random.normal(2, 1, 50)
data4 = np.random.normal(3, 1, 50)
Plot data on each subplot
axs[0, 0].plot(data1)
axs[0, 1].plot(data2)
axs[1, 0].plot(data3)
axs[1, 1].plot(data4)
Set title and labels for each subplot
for ax in axs.flat:
ax.set_title('Subplot ' + str(axs.tolist().index(ax) + 1))
ax.label_outer()
plt.show()
In this example, we create a 2x2 grid with four subplots. Each subplot displays a different dataset, and the x-axis is shared across all subplots in each row (due to `sharex='all'`).
Worked Example
In this example, we will create a line plot for the function y = sin(x) and its derivative y' = cos(x) using Matplotlib subplot.
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad
Define the functions for the plots
def sin_func(x): return np.sin(x)
def cos_func(x): return np.cos(x)
Create a 2x1 grid with shared x-axis and separate y-axes
fig, axs = plt.subplots(2, 1, figsize=(8,6), sharex='all')
Plot the sin function
axs[0].plot(np.linspace(0, 2np.pi, 500), sin_func(np.linspace(0, 2np.pi, 500)))
axs[0].set_title('y = sin(x)')
axs[0].label_outer()
Calculate the antiderivative of cos(x) using numerical integration and plot it
def integrate_cos(x): return quad(lambda t: np.cos(t), 0, x)[0]
axs[1].plot(np.linspace(0, 2np.pi, 500), integrate_cos(np.linspace(0, 2np.pi, 500)))
axs[1].set_title('y' + '\u2032 = cos(x)')
axs[1].label_outer()
plt.show()
In this example, we create a 2x1 grid with two subplots. The first subplot displays the `sin(x)` function, and the second subplot shows the antiderivative of `cos(x)`. Both subplots share the x-axis (due to `sharex='all'`).
Common Mistakes
- Forgetting to specify
figsizeor setting it incorrectly, resulting in a figure that is too small or large for the subplots. - Not sharing the x-axis (or y-axis) when needed, causing the plots to have separate axes with different scales.
- Not labeling the subplots or providing proper titles, making it difficult to understand which plot corresponds to which dataset.
- Using
subplot()incorrectly, such as specifying too many rows and columns for the number of subplots you want to create.
Subheadings under Common Mistakes:
- Incorrect figure size
- Separate axes with different scales
- Unlabeled or improperly titled subplots
- Incorrect use of
subplot()
Practice Questions
- Create a 3x2 grid with shared x-axis and separate y-axes, and plot three different datasets on each subplot.
- Modify the worked example to include error bars on both the sin function and its derivative.
- Use
subplot()to create a scatter plot of two datasets in one figure, with separate x- and y-axes for each dataset.
Subheadings under Practice Questions:
- Creating multiple subplots with shared axes
- Adding error bars to plots
- Creating scatter plots with separate axes for each dataset
FAQ
A: You can adjust the wspace (width of the whitespace between subplots) and hspace (height of the whitespace between subplots) parameters in subplot(). For example, subplot(2, 2, 1, wspace=0.1, hspace=0.1) will create a smaller gap between subplots.
Q: How do I rotate the x-axis labels?
A: You can use the rotation parameter in xticks() to rotate the x-axis labels. For example, ax.xticks(rotation=45) will rotate the x-axis labels by 45 degrees.
Q: How do I customize the grid lines?
A: You can use the grid() function to display grid lines and the grid.set_linewidth() function to adjust their thickness. For example, ax.grid(True, which='both', linestyle='-', linewidth=1) will display both major and minor grid lines with a line width of 1.
Subheadings under FAQ:
- Adjusting the space between subplots
- Rotating x-axis labels
- Customizing grid lines