Matplotlib Subplots
Matplotlib is a powerful data visualization library in Python that allows you to create various types of plots, such as line plots, bar plots, scatter plots, and more. One of the key features of Matplotlib is the ability to create subplots, which allow you to display multiple plots in a single figure. In this article, we will explore how to use subplots in Matplotlib and provide numerous code examples to illustrate their usage.
Overview of Matplotlib Subplots
Subplots are essentially a grid of plots within a single figure. They provide a convenient way to compare and contrast multiple plots, making it easier to analyze and understand your data. Each subplot is defined by its position in the grid, which can be specified using row and column indices.
You can create subplots in Matplotlib using the subplots()
function, which returns a figure object and an array of axes objects. The figure object represents the entire figure, while each axis object represents an individual subplot.
Here is the syntax for creating subplots:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows, ncols)
The nrows
and ncols
parameters specify the number of rows and columns in the subplot grid, respectively. The fig
object represents the entire figure, and the axes
object is an array of axis objects, one for each subplot.
Matplotlib Subplot Grid
Before we dive into code examples, let’s take a look at the concept of a subplot grid. The subplot grid is a matrix-like structure that specifies the position of each subplot within the figure. The grid is defined by the number of rows and columns specified when creating subplots.
For example, if we create a subplot grid with 2 rows and 2 columns, the grid will look like this:
+-----+-----+
| 1 | 2 |
+-----+-----+
| 3 | 4 |
+-----+-----+
Each number represents the position of a subplot within the grid. For instance, (1, 1)
corresponds to the top-left subplot, (1, 2)
corresponds to the top-right subplot, (2, 1)
corresponds to the bottom-left subplot, and (2, 2)
corresponds to the bottom-right subplot.
Matplotlib Subplots Code Examples
Now let’s explore some code examples to demonstrate the usage of subplots in Matplotlib. Here are 10 examples that show different scenarios of creating and customizing subplots.
Example 1: Simple Line Plot
In this example, we create a figure with a single subplot and plot a simple line graph.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi, np.pi, 100)
Y = np.sin(X)
fig, ax = plt.subplots()
ax.plot(X, Y)
plt.show()
Output:
Example 2: Multiple Subplots
In this example, we create a figure with multiple subplots and plot different types of plots in each subplot.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-5, 5, 100)
Y1 = X ** 2
Y2 = np.exp(X)
Y3 = np.sin(X)
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
axes[0].plot(X, Y1)
axes[0].set_title('Quadratic Plot')
axes[1].plot(X, Y2)
axes[1].set_title('Exponential Plot')
axes[2].plot(X, Y3)
axes[2].set_title('Sine Plot')
plt.tight_layout()
plt.show()
Output:
Example 3: Subplots with Grid Specification
In this example, we create a figure with a custom subplot grid specification and plot different types of plots.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-5, 5, 100)
Y1 = X ** 2
Y2 = np.exp(X)
Y3 = np.sin(X)
fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(X, Y1)
ax1.set_title('Quadratic Plot')
ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(X, Y2)
ax2.set_title('Exponential Plot')
ax3 = fig.add_subplot(2, 2, 3)
ax3.plot(X, Y3)
ax3.set_title('Sine Plot')
plt.tight_layout()
plt.show()
Output:
Example 4: Sharing Axis
In this example, we create a figure with multiple subplots that share the x-axis and y-axis.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi, np.pi, 100)
Y1 = np.sin(X)
Y2 = np.cos(X)
fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
axes[0].plot(X, Y1)
axes[0].set_title('Sine Plot')
axes[1].plot(X, Y2)
axes[1].set_title('Cosine Plot')
plt.tight_layout()
plt.show()
Output:
Example 5: Subplots with Different Sizes
In this example, we create a figure with subplots of different sizes.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_axes([0.1, 0.1, 0.7, 0.7])
ax1.set_title('Large Subplot')
ax2 = fig.add_axes([0.8, 0.2, 0.2, 0.3])
ax2.set_title('Small Subplot')
plt.tight_layout()
plt.show()
Output:
Example 6: Subplots with Different Orientations
In this example, we create a figure with subplots arranged in different orientations.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 6))
axes[0, 0].set_title('Top-Left')
axes[0, 1].set_title('Top-Center')
axes[0, 2].set_title('Top-Right')
axes[1, 0].set_title('Bottom-Left')
axes[1, 1].set_title('Bottom-Center')
axes[1, 2].set_title('Bottom-Right')
plt.tight_layout()
plt.show()
Output:
Example 7: Subplots with Shared X-Axis
In this example, we create a figure with subplots that share the x-axis.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi, np.pi, 100)
Y1 = np.sin(X)
Y2 = np.cos(X)
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
ax1.plot(X, Y1)
ax1.set_title('Sine Plot')
ax2.plot(X, Y2)
ax2.set_title('Cosine Plot')
plt.tight_layout()
plt.show()
Output:
Example 8: Subplots with Grid Spec
In this example, we create a figure with subplots using the GridSpec
module.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax1.set_title('Top-Left')
ax2 = fig.add_subplot(gs[0, 1])
ax2.set_title('Top-Right')
ax3 = fig.add_subplot(gs[1, :])
ax3.set_title('Bottom')
plt.tight_layout()
plt.show()
Output:
Example 9: Subplots with Colorbar
In this example, we create a figure with subplots that include a colorbar.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
Z = np.sqrt(X**2 + Y**2)
fig, axes = plt.subplots(nrows=1, ncols=2)
im1 = axes[0].imshow(Z)
axes[0].set_title('Plot 1')
fig.colorbar(im1, ax=axes[0])
im2 = axes[1].imshow(Z)
axes[1].set_title('Plot 2')
fig.colorbar(im2, ax=axes[1])
plt.tight_layout()
plt.show()
Output:
Example 10: Subplots with Annotations
In this example, we create a figure with subplots and add annotations to highlight specific points.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-5, 5, 100)
Y = X ** 2
fig, ax = plt.subplots()
ax.plot(X, Y)
ax.set_title('Quadratic Plot')
ax.annotate('Minimum', xy=(0, 0), xytext=(2, 20),
arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.show()
Output:
Matplotlib Subplots Conclusion
Matplotlib subplots provide a powerful way to arrange and visualize multiple plots within a single figure. By using subplots, you can create complex visualizations that offer deeper insights into your data. In this article, we explored various code examples that demonstrate different scenarios of using subplots in Matplotlib. With these examples, you should now have a good understanding of how to create and customize subplots to suit your specific needs.