Tutorial: How to have Multiple Plots on Same Figure in Matplotlib

Introduction

Matplotlib is a powerful library for data visualization in Python. It provides a wide range of tools for creating various types of plots, including line plots, scatter plots, histograms, and more. In this tutorial, we will explore how to have multiple plots on the same figure in Matplotlib.

Having multiple plots on the same figure can be useful when you want to compare different datasets or display different aspects of the same dataset. Matplotlib makes it easy to create multiple plots on the same figure using its subplots() function.

Let’s dive into the details of how to achieve this in Matplotlib.

Understanding Matplotlib

Matplotlib is a Python library used for data visualization. It provides a wide range of tools for creating various types of charts, graphs, and plots. Matplotlib is widely used in the scientific community, especially in the fields of physics, engineering, and mathematics.

Matplotlib provides two interfaces for creating plots: the pyplot interface and the object-oriented interface. The pyplot interface is a procedural interface that allows you to create and manipulate figures and axes in a simple way. The object-oriented interface is more flexible and allows you to have more control over your plots.

In this tutorial, we will be using the pyplot interface to create multiple plots on the same figure. Before we proceed with the tutorial, let’s make sure that Matplotlib is installed on your system. You can install it by running the following command:


!pip install matplotlib

Once Matplotlib is installed, we can start creating our plots.

Creating Multiple Plots on Same Figure using add_subplot()

In data visualization, it is often necessary to have multiple plots on the same figure in order to compare and contrast different aspects of the data. Matplotlib, a popular Python library for data visualization, provides an easy way to create multiple plots on the same figure using the `add_subplot()` method.

The `add_subplot()` method takes three arguments: the number of rows, the number of columns, and the index of the plot. The index starts from 1 in the upper left corner and goes row by row.

Let’s say we want to create a figure with two subplots, one above the other. We can do this by calling `add_subplot()` twice with the arguments `(2, 1, 1)` and `(2, 1, 2)` respectively. Here is how we can accomplish this:


import matplotlib.pyplot as plt

# Create a figure with two subplots
fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

# Plot some data on each subplot
ax1.plot([1, 2, 3], [4, 5, 6])
ax2.plot([1, 2, 3], [6, 5, 4])

# Add labels and titles
ax1.set_xlabel('X Label')
ax1.set_ylabel('Y Label')
ax2.set_xlabel('X Label')
ax2.set_ylabel('Y Label')

plt.suptitle('Two Subplots on Same Figure')

# Display the plot
plt.show()

In this code block we first import `matplotlib.pyplot` as `plt`. Then we create a new figure with a size of `(8,6)` using `plt.figure()`, which returns an instance of `Figure`. We then use `fig.add_subplot()` to create two subplots, `ax1` and `ax2`, with arguments `(2, 1, 1)` and `(2, 1, 2)` respectively.

Next, we plot some data on each subplot using the `plot()` method of each `AxesSubplot` object. We then add labels and titles to each subplot using the `set_xlabel()`, `set_ylabel()`, and `set_title()` methods. Finally, we call `plt.suptitle()` to add a title to the entire figure.

We can see that calling `add_subplot()` twice has created a figure with two subplots stacked vertically. The first subplot shows a line plot of `[1,2,3]` against `[4,5,6]`, while the second subplot shows a line plot of `[1,2,3]` against `[6,5,4]`.

Overall, using `add_subplot()` is a simple and effective way to create multiple plots on the same figure in Matplotlib.

Creating Multiple Plots on Same Figure using subplots()

When creating visualizations, it is often useful to have multiple plots on the same figure. This can help compare different data sets or visualize different aspects of the same data. In Matplotlib, we can achieve this using the `subplots()` function.

The `subplots()` function creates a grid of subplots within a single figure. We can specify the number of rows and columns in the grid, as well as the size of each subplot. Here’s an example:


import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(8, 6))

In this example, we create a figure with a 2×2 grid of subplots and a total size of 8×6 inches. The `subplots()` function returns two objects: the figure object (`fig`) and an array of axes objects (`axs`). We can use these axes objects to plot our data on each subplot.

To plot on a specific subplot, we simply index into the `axs` array using the row and column numbers. For example, to plot on the top left subplot:


axs[0, 0].plot(x1, y1)

Here, `x1` and `y1` are arrays of data that we want to plot on the top left subplot.

We can customize each subplot individually using its corresponding axes object. For example, we can set the title of the top left subplot like this:


axs[0, 0].set_title('Top Left Subplot')

Overall, using `subplots()` is a convenient way to create multiple plots on the same figure in Matplotlib. It allows us to easily compare different data sets or visualize different aspects of the same data within a single visualization.

Customizing Multiple Plots on Same Figure

When creating multiple plots on the same figure using Matplotlib, it is often necessary to customize each plot to make them more visually appealing and informative. In this section, we will cover some of the ways to customize multiple plots on the same figure.

1. Setting Titles and Labels: You can set titles and labels for each individual plot by using the `set_title()` and `set_xlabel()`/`set_ylabel()` methods respectively. For example:


import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title('Plot 1')
ax1.set_xlabel('X Label')
ax1.set_ylabel('Y Label')

ax2.plot([4, 5, 6], [7, 8, 9])
ax2.set_title('Plot 2')
ax2.set_xlabel('X Label')
ax2.set_ylabel('Y Label')

plt.show()

In this example, we created two plots on the same figure and set titles and labels for each plot using the appropriate methods.

2. Setting Limits: You can set limits for each individual plot using the `set_xlim()` and `set_ylim()` methods. For example:


import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title('Plot 1')
ax1.set_xlim([0,4])
ax1.set_ylim([0,7])

ax2.plot([4, 5, 6], [7, 8, 9])
ax2.set_title('Plot 2')
ax2.set_xlim([3,7])
ax2.set_ylim([6,10])

plt.show()

In this example, we set different limits for each plot using the appropriate methods.

3. Adding Legends: You can add a legend to each individual plot using the `legend()` method. For example:


import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot([1, 2, 3], [4, 5, 6], label='Line A')
ax1.plot([1, 2, 3], [7, 8, 9], label='Line B')
ax1.set_title('Plot 1')
ax1.legend()

ax2.plot([4, 5, 6], [7, 8, 9], label='Line C')
ax2.plot([4, 5, 6], [10, 11, 12], label='Line D')
ax2.set_title('Plot 2')
ax2.legend()

plt.show()

In this example, we added legends to each plot by providing a label for each line and calling the `legend()` method.

These are just some of the ways to customize multiple plots on the same figure in Matplotlib. Experiment with different options to make your plots more visually appealing and informative.

Conclusion

In this tutorial, we have learned how to create multiple plots on the same figure in Matplotlib. We have explored two different methods of achieving this – using `subplot()` and `add_subplot()`.

Using `subplot()` is a simple and straightforward method for creating multiple plots on the same figure. It allows us to specify the number of rows and columns of subplots we want, as well as the position of each subplot within the grid. We can then plot our data onto each individual subplot using the corresponding axes object.

Alternatively, we can use `add_subplot()` to add subplots to a figure one by one. This method gives us more control over the layout and positioning of our subplots, but requires a bit more code to set up.

Regardless of which method you choose, having multiple plots on the same figure can be a powerful tool for visualizing complex data sets and comparing different aspects of your data side-by-side. With these techniques in your toolbox, you’ll be well-equipped to create informative and engaging visualizations with Matplotlib.
Interested in learning more? Check out our Introduction to Python course!


How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!


Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]