Mastering Data Visualization with Matplotlib in Python

4.03K 0 0 0 0

Chapter 4: Working with Subplots and Multiple Axes

🔹 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:

  • How to create subplots in Matplotlib
  • How to organize subplots in grids (rows and columns)
  • How to adjust the layout of subplots for optimal use of space
  • How to create plots with multiple axes (sharing or independent)
  • How to work with multiple plots (with customized titles, labels, and legends)

🔹 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:

  • hspace controls the vertical space between subplots.
  • wspace controls the horizontal space between subplots.

🔹 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:

  • fig.add_axes([left, bottom, width, height]) manually specifies the position of the axes within the figure.
  • The axes are independent and do not share the same x or y scales.

🔹 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:

  • The first row shows a line plot and a scatter plot.
  • The second row shows a bar plot and a histogram.
  • All subplots share the x-axis for easier comparison.

🔹 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

Back

FAQs


1. What is Matplotlib in Python?

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.

2. How do I install Matplotlib?

  1. Matplotlib can be installed using the Python package manager pip:


pip install matplotlib

3. What are the most common plot types in Matplotlib?

Some of the most common plot types include line plots, bar charts, scatter plots, histograms, and pie charts.

4. How can I change the style of a plot in Matplotlib?

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.

5. How can I save a Matplotlib plot as an image?

  1. You can save a Matplotlib plot as an image file using the savefig() method:


plt.savefig('plot.png')

6. What is the difference between plt.show() and plt.savefig()?

plt.show() displays the plot on the screen, while plt.savefig() saves the plot as an image file (e.g., PNG, JPEG, SVG, PDF).

7. Can Matplotlib be used for interactive plots?

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.

8. How do I create a pie chart in Matplotlib?

  1. Use the plt.pie() function to create pie charts:

sizes = [10, 20, 30, 40]

labels = ['A', 'B', 'C', 'D']

plt.pie(sizes, labels=labels)


plt.show()

9. Can I create 3D plots with Matplotlib?

Yes, Matplotlib supports 3D plotting via the Axes3D module. You can create 3D scatter plots, surface plots, and more

10. How do I change the figure size in Matplotlib?

  1. You can change the figure size using plt.figure(figsize=(width, height)):


plt.figure(figsize=(10, 6))  # Set figure size to 10x6 inches