Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🔹 1. Introduction
In this chapter, we will explore how to create subplots
in Matplotlib, allowing you to organize multiple plots in a single figure. This
feature is especially useful when you need to compare multiple datasets,
visualizations, or multiple representations of the same data side by side. By
the end of this chapter, you'll be able to create and customize complex plots
using subplots and multiple axes.
In Matplotlib, a figure is the entire window or page
that contains the plot, while axes are individual subplots within the
figure. You can have multiple axes within a single figure, and each axis can
contain a different plot type (such as line, bar, scatter, etc.).
What You’ll Learn in This Chapter:
🔹 2. Creating Subplots in
Matplotlib
The plt.subplots() function is used to create a grid of
subplots in a figure. It returns a figure object and an axes
array, which you can use to customize each subplot individually.
✅ Creating a Single Plot in a
Grid
You can create a single plot in a grid of multiple plots by
specifying 1 row and 1 column:
import
matplotlib.pyplot as plt
#
Create a 1x1 grid of subplots (1 row, 1 column)
fig,
ax = plt.subplots(1, 1)
#
Plot data on the single axis
x
= [1, 2, 3, 4, 5]
y
= [1, 4, 9, 16, 25]
ax.plot(x,
y)
#
Display the plot
plt.show()
In this example, fig, ax = plt.subplots(1, 1) creates a
single plot (since there’s only one row and one column).
✅ Creating Multiple Subplots in a
Grid
If you want to create multiple plots, you can define the
number of rows and columns in the grid:
fig,
ax = plt.subplots(2, 2) # Create a 2x2
grid (2 rows, 2 columns)
#
Plot data on each subplot
ax[0,
0].plot(x, y) # First subplot
ax[0,
1].scatter(x, y) # Second subplot
ax[1,
0].bar(x, y) # Third subplot
ax[1,
1].hist(y) # Fourth subplot
#
Display the plot
plt.tight_layout() # Adjust the layout to avoid overlap
plt.show()
In this example, fig, ax = plt.subplots(2, 2) creates a 2x2
grid. The axes array (ax) contains a 2D array of axes, and you can
access each individual subplot using ax[row, column].
🔹 3. Sharing Axes Between
Subplots
Sometimes, it’s useful to share axes between multiple
subplots. This is particularly helpful when you want to compare plots with the
same scale (e.g., sharing the x-axis or y-axis).
✅ Sharing the X-Axis
You can create subplots with a shared x-axis by
passing sharex=True to plt.subplots():
fig,
ax = plt.subplots(2, 1, sharex=True) # 2
rows, 1 column, sharing x-axis
#
Plot data on each subplot
ax[0].plot(x,
y)
ax[1].scatter(x,
y)
#
Display the plot
plt.show()
In this case, both subplots will share the same x-axis,
which makes it easier to compare the data visually.
✅ Sharing the Y-Axis
Similarly, you can share the y-axis between subplots
by passing sharey=True:
fig,
ax = plt.subplots(1, 2, sharey=True) # 1
row, 2 columns, sharing y-axis
#
Plot data on each subplot
ax[0].plot(x,
y)
ax[1].scatter(x,
y)
#
Display the plot
plt.show()
This will make the y-axis the same for both subplots,
helping you compare the data more accurately.
🔹 4. Customizing the
Layout of Subplots
You may want to adjust the spacing between your subplots for
better readability. The plt.tight_layout() function automatically adjusts the
subplot parameters to minimize overlap between subplots.
✅ Adjusting the Spacing
fig,
ax = plt.subplots(2, 2)
ax[0,
0].plot(x, y)
ax[0,
1].scatter(x, y)
ax[1,
0].bar(x, y)
ax[1,
1].hist(y)
#
Automatically adjust subplot parameters
plt.tight_layout()
plt.show()
✅ Adjusting Subplot Parameters
Manually
You can manually adjust the spacing using
plt.subplots_adjust():
fig,
ax = plt.subplots(2, 2)
ax[0,
0].plot(x, y)
ax[0,
1].scatter(x, y)
ax[1,
0].bar(x, y)
ax[1,
1].hist(y)
#
Manually adjust spacing
plt.subplots_adjust(hspace=0.5,
wspace=0.5)
plt.show()
Here:
🔹 5. Using Multiple Axes
for Different Plots
Sometimes, you may want to create plots with completely
different axes (i.e., not sharing the same axis). You can do this by manually
creating axes using fig.add_axes() or fig.add_subplot().
✅ Creating Multiple Axes with
add_axes()
fig
= plt.figure(figsize=(10, 5))
#
Create the first axes object
ax1
= fig.add_axes([0.1, 0.1, 0.4, 0.8]) #
[left, bottom, width, height]
ax1.plot(x,
y, color='blue')
#
Create the second axes object
ax2
= fig.add_axes([0.6, 0.1, 0.4, 0.8])
ax2.scatter(x,
y, color='red')
plt.show()
In this example:
🔹 6. Example: Creating a
Complex Plot Layout
Here’s an example where we combine multiple subplots
with customized axes, different plot types, and shared axes:
fig,
ax = plt.subplots(2, 2, sharex=True, figsize=(10, 8))
#
First subplot
ax[0,
0].plot(x, y, label='Line Plot')
ax[0,
0].set_title('Line Plot')
ax[0,
0].legend()
#
Second subplot
ax[0,
1].scatter(x, y, color='green', label='Scatter Plot')
ax[0,
1].set_title('Scatter Plot')
ax[0,
1].legend()
#
Third subplot
ax[1,
0].bar(x, y, color='purple', label='Bar Plot')
ax[1,
0].set_title('Bar Plot')
ax[1,
0].legend()
#
Fourth subplot
ax[1,
1].hist(y, bins=5, color='orange', label='Histogram')
ax[1,
1].set_title('Histogram')
ax[1,
1].legend()
#
Automatically adjust the layout
plt.tight_layout()
plt.show()
In this complex plot:
🔹 7. Summary Table
Operation |
Function/Method |
Description |
Create
Subplots |
plt.subplots() |
Create
multiple plots in a grid layout |
Share Axes |
sharex=True,
sharey=True |
Share the x
or y axes between subplots |
Adjust Layout |
plt.tight_layout() |
Adjust the
layout to avoid overlap |
Manually
Adjust Spacing |
plt.subplots_adjust() |
Adjust the
spacing between subplots |
Add Multiple
Axes |
fig.add_axes() |
Manually add
independent axes |
Create
Multiple Plot Types |
plt.plot(),
plt.scatter(), etc. |
Create
different plot types in subplots |
Matplotlib is a powerful Python library used for creating static, animated, and interactive visualizations. It provides extensive control over plot design and is used by data scientists and analysts for visualizing data.
pip install matplotlib
Some of the most common plot types include line plots, bar charts, scatter plots, histograms, and pie charts.
Matplotlib offers various customization options, including color, line style, markers, axis labels, titles, and more. You can use functions like plt.plot(), plt.title(), plt.xlabel(), and plt.ylabel() to modify the style.
plt.savefig('plot.png')
plt.show() displays the plot on the screen, while plt.savefig() saves the plot as an image file (e.g., PNG, JPEG, SVG, PDF).
Yes, Matplotlib supports interactive features, such as zooming, panning, and hovering over elements. For even more advanced interactivity, you can combine Matplotlib with libraries like Plotly or Bokeh.
sizes = [10, 20, 30, 40]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels)
plt.show()
Yes, Matplotlib supports 3D plotting via the Axes3D module. You can create 3D scatter plots, surface plots, and more
plt.figure(figsize=(10, 6)) # Set figure size to 10x6 inches
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)