Matplotlib Subplot

In Matplotlib, subplots allow you to create multiple plots within the same figure, enabling you to display different data visualizations side by side. This is useful for comparing data, showing different views of the same dataset, or creating dashboards with multiple charts. Matplotlib provides several ways to create subplots, each with different levels of flexibility.

Here are the main methods for creating subplots in Matplotlib:

1. Creating Subplots with plt.subplot()

The plt.subplot() function is used to create subplots by specifying the number of rows, columns, and the index of the current subplot.

The syntax is:

plt.subplot(nrows, ncols, index)

Where:

  • nrows: The number of rows in the grid.
  • ncols: The number of columns in the grid.
  • index: The index of the subplot you’re currently working on (1-based).

Example 1: Two Subplots in a Single Row

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 40]
y2 = [40, 30, 25, 20, 10]

# First subplot
plt.subplot(1, 2, 1)  # 1 row, 2 columns, subplot 1
plt.plot(x, y1)
plt.title("Plot 1")

# Second subplot
plt.subplot(1, 2, 2)  # 1 row, 2 columns, subplot 2
plt.plot(x, y2)
plt.title("Plot 2")

# Show the plot
plt.show()

This creates two plots side by side in a single row.

Example 2: Four Subplots in a 2×2 Grid

# First subplot
plt.subplot(2, 2, 1)
plt.plot(x, y1)
plt.title("Plot 1")

# Second subplot
plt.subplot(2, 2, 2)
plt.plot(x, y2)
plt.title("Plot 2")

# Third subplot
plt.subplot(2, 2, 3)
plt.plot(x, [i**2 for i in x])
plt.title("Plot 3")

# Fourth subplot
plt.subplot(2, 2, 4)
plt.plot(x, [i**3 for i in x])
plt.title("Plot 4")

# Show the plot
plt.show()

This creates four subplots arranged in a 2×2 grid.

2. Using plt.subplots() for More Flexibility

The plt.subplots() function is more flexible and returns a figure and an array of axes (subplots). This is the preferred method for creating complex subplot layouts, as it allows for more control over the figure and individual axes.

The syntax is:

fig, axes = plt.subplots(nrows, ncols)

Example 1: Two Subplots in a Single Column

# Create a figure and an array of axes with 2 rows and 1 column
fig, axes = plt.subplots(2, 1)

# First subplot
axes[0].plot(x, y1)
axes[0].set_title("Plot 1")

# Second subplot
axes[1].plot(x, y2)
axes[1].set_title("Plot 2")

# Adjust layout to prevent overlap
plt.tight_layout()

plt.show()

Here, axes is an array of subplots, and each subplot is accessed using axes[0], axes[1], etc.

Example 2: Four Subplots with Custom Sizes

You can customize the figure size and layout by passing parameters like figsize to control the overall size of the figure.

# Create a 2x2 grid of subplots with a custom figure size
fig, axes = plt.subplots(2, 2, figsize=(10, 6))

# First subplot
axes[0, 0].plot(x, y1)
axes[0, 0].set_title("Plot 1")

# Second subplot
axes[0, 1].plot(x, y2)
axes[0, 1].set_title("Plot 2")

# Third subplot
axes[1, 0].plot(x, [i**2 for i in x])
axes[1, 0].set_title("Plot 3")

# Fourth subplot
axes[1, 1].plot(x, [i**3 for i in x])
axes[1, 1].set_title("Plot 4")

# Adjust layout to prevent overlap
plt.tight_layout()

plt.show()

Here, axes[0, 0], axes[0, 1], axes[1, 0], and axes[1, 1] correspond to each subplot in the 2×2 grid.

3. Sharing Axes Between Subplots

You can share the x-axis and/or y-axis between subplots by passing the sharex and sharey parameters to plt.subplots(). This ensures that the axes are synchronized, and changes in one subplot affect the others.

Example: Shared X-Axis

# Create subplots with shared x-axis
fig, axes = plt.subplots(2, 1, sharex=True)

# First subplot
axes[0].plot(x, y1)
axes[0].set_title("Plot 1")

# Second subplot
axes[1].plot(x, y2)
axes[1].set_title("Plot 2")

# Show the plot
plt.show()

In this case, both subplots share the same x-axis, so zooming or panning in one subplot will affect the other.

4. Subplot Spacing with plt.subplots_adjust()

You can adjust the spacing between subplots using the plt.subplots_adjust() function. This is useful when subplots overlap or when you want to control the distance between them.

The syntax is:

plt.subplots_adjust(left, right, top, bottom, wspace, hspace)
  • left, right, top, bottom: Control the position of the subplots in the figure.
  • wspace: Width space between subplots.
  • hspace: Height space between subplots.

Example: Increasing Space Between Subplots

fig, axes = plt.subplots(2, 1)

# First subplot
axes[0].plot(x, y1)
axes[0].set_title("Plot 1")

# Second subplot
axes[1].plot(x, y2)
axes[1].set_title("Plot 2")

# Adjust the space between subplots
plt.subplots_adjust(hspace=0.5)

plt.show()

This increases the vertical space between the two subplots.

5. GridSpec for Complex Layouts

For more control over subplot positioning, you can use GridSpec. This allows you to specify more complex subplot arrangements, such as subplots that span multiple rows or columns.

import matplotlib.gridspec as gridspec

# Create a 2x2 grid
fig = plt.figure()

# Define the GridSpec layout
gs = gridspec.GridSpec(2, 2)

# Create subplots that span multiple rows or columns
ax1 = fig.add_subplot(gs[0, 0])  # First row, first column
ax2 = fig.add_subplot(gs[0, 1])  # First row, second column
ax3 = fig.add_subplot(gs[1, :])  # Second row, spans both columns

# Plot data
ax1.plot(x, y1)
ax2.plot(x, y2)
ax3.plot(x, [i**2 for i in x])

# Add titles
ax1.set_title("Plot 1")
ax2.set_title("Plot 2")
ax3.set_title("Plot 3")

plt.tight_layout()
plt.show()

In this example, ax3 spans both columns in the second row, while ax1 and ax2 are in the first row.

6. Subplots with plt.twinx() (Dual Y-Axis)

The plt.twinx() function allows you to create a subplot with two y-axes, sharing the same x-axis. This is useful for comparing two datasets with different y-ranges.

# Create a figure and a set of subplots
fig, ax1 = plt.subplots()

# Plot data on the first y-axis
ax1.plot(x, y1, 'g-')
ax1.set_ylabel('Y1 data', color='g')

# Create a second y-axis that shares the same x-axis
ax2 = ax1.twinx()
ax2.plot(x, y2, 'b-')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

This creates a plot with two different y-axes, one for y1 and one for y2.

Conclusion

Subplots in Matplotlib provide a powerful way to display multiple plots in one figure. Whether you need a simple grid of plots, shared axes, or more complex layouts, Matplotlib offers flexibility and control over how your data is presented. The combination of plt.subplot(), plt.subplots(), and GridSpec provides you with various options for organizing your plots effectively.

Leave a Reply 0

Your email address will not be published. Required fields are marked *