I want to share a fun little project I recently worked on where I created a 2×2 grid of subplots using Python’s Matplotlib library. This method is super handy for visualizing and comparing different functions side by side. In my example, I plotted four distinct functions: sine, cosine, a function with a vertical asymptote, and exponential. By the end of this post, you’ll see how straightforward it is to create multiple plots in a single figure.
My Code Snippet
Below is the concise code I used. Feel free to copy and run it in your favorite Python environment—be it a Jupyter notebook or a standard Python script.
import numpy as np
import matplotlib.pyplot as plt
# Generate a range of x values
x = np.linspace(0, 4, 200)
# Create a 2×2 grid of subplots
fig, ax = plt.subplots(2, 2, figsize=(8, 6))
# Top-left: Sine function
ax[0, 0].plot(x, np.sin(x), color='blue')
ax[0, 0].set_title("Sine")
ax[0, 0].set_xlabel("x")
ax[0, 0].set_ylabel("sin(x)")
# Top-right: Cosine function
ax[0, 1].plot(x, np.cos(x), color='red')
ax[0, 1].set_title("Cosine")
ax[0, 1].set_xlabel("x")
ax[0, 1].set_ylabel("cos(x)")
# Bottom-left: A function with an asymptote (1 / (x - 2))
# We'll clip the domain to avoid the singularity at x=2
x_asym = np.linspace(0, 1.9, 100)
x_asym2 = np.linspace(2.1, 4, 100)
ax[1, 0].plot(x_asym, 1/(x_asym - 2), color='green')
ax[1, 0].plot(x_asym2, 1/(x_asym2 - 2), color='green')
ax[1, 0].set_title("1 / (x - 2)")
ax[1, 0].set_xlabel("x")
ax[1, 0].set_ylabel("f(x)")
# Bottom-right: Exponential function
ax[1, 1].plot(x, np.exp(x), color='magenta')
ax[1, 1].set_title("Exponential")
ax[1, 1].set_xlabel("x")
ax[1, 1].set_ylabel("e^x")
# Adjust the layout to prevent overlapping labels
plt.tight_layout()
# Display the figure
plt.show()
Breaking Down the Code
- Imports
numpy
for numerical operations (like creating arrays and usinglinspace
).matplotlib.pyplot
for plotting the functions.
- Data Creation
- I used
np.linspace(0, 4, 200)
to generate 200 points between 0 and 4. This gives me a smooth set of x-values for my sine, cosine, and exponential functions. - For the asymptotic function 1x−2\frac{1}{x – 2}x−21, I avoided the singularity at x=2x = 2x=2 by splitting the domain into two parts:
0 to 1.9
2.1 to 4
- I used
- Setting Up Subplots
fig, ax = plt.subplots(2, 2, figsize=(8, 6))
creates a 2×2 grid of subplots, which I store in theax
array.figsize=(8, 6)
adjusts the overall figure size.
- Plotting Each Function
- Top-left (Sine):
ax[0, 0].plot(x, np.sin(x), color='blue')
- Top-right (Cosine):
ax[0, 1].plot(x, np.cos(x), color='red')
- Bottom-left (Asymptote):
ax[1, 0].plot(...)
uses two separate ranges for xxx to avoid the vertical asymptote at x=2x = 2x=2. - Bottom-right (Exponential):
ax[1, 1].plot(x, np.exp(x), color='magenta')
- Top-left (Sine):
- Layout and Display
plt.tight_layout()
ensures that the subplots don’t overlap or cut off labels.- Finally,
plt.show()
displays the entire figure on your screen.
Why Subplots?
I really enjoy using subplots because they allow me to:
- Compare Different Functions or Data Sets: Having them side by side helps me see how they behave relative to each other.
- Keep Plots Organized: It’s neater to group related plots in one figure rather than having separate windows or files.
- Reuse the Same Range of x-values: By keeping the domain consistent, I can quickly notice similarities or differences in the behavior of various functions.
Final Thoughts
This little project taught me how convenient and flexible subplots can be for data visualization. By splitting my plots into a 2×2 grid, I was able to compare four different functions without clutter. You can adapt this structure for any set of functions or data you want to visualize side by side. Feel free to change the color schemes, add legends, or include more subplots if needed!