Managing multiple plots in a single figure in Matplotlib

Matplotlib, a powerful and versatile plotting library in Python, offers extensive capabilities for creating a wide range of visualizations. Managing multiple plots within a single figure becomes crucial when working with complex datasets or exploring different aspects of data. This answer will explore the techniques for managing and selecting subplots in Matplotlib, empowering the users to enhance their data visualization skills.

Understanding subplots in Matplotlib

A subplot refers to a smaller plot within a larger figure. Matplotlib provides a simple and effective way to arrange and manage subplots, allowing users to display multiple plots in a single figure. The subplot() function is a key tool that is used to create subplots within a single figure. It takes three arguments: the number of rows, the number of columns, and the index of the subplot to be created. Here’s the basic syntax:

plt.subplot(nrows, ncols, index)

Multiple subplots in a single figure

Now, let’s dive in with an example that demonstrates how to effectively manage multiple plots while using the subplot() command.

import matplotlib.pyplot as plt
import numpy as np
# Defining values to plot
x = np.arange(-2.0, 2.0, 0.01)
l1 = x**2
l2 = np.sin(np.pi*x)
l3 = -x**2
# Select first subplot
plt.subplot(211)
# Plot a line on it.
plt.plot(x, l1)
# Select second subplot.
plt.subplot(212)
# Plot a line on it.
plt.plot(x, l2)
# Select first subplot again.
plt.subplot(211)
# Add another line in that plot.
plt.plot(x, l3)

In this example, we create a figure with a 2x1 grid of subplots.

  • Line 11: We select the first subplot using plt.subplot(211).

  • Line 13: We plot a line (l1) on it.

  • Line 16: We select the second subplot using plt.subplot(212).

  • Line 18: We plot a different line (l2).

  • Line 21: Finally, we go back to the first subplot using plt.subplot(211).

  • Line 23: We plot another line (l3) on the first subplot.

Conclusion

Mastering the management of multiple plots in a single figure is a valuable skill for data scientists, analysts, and anyone working with visualizations. Knowing how to switch between different plots while working with multiple plots is a useful skill to have in your arsenal.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved