Matplotlib Tutorial: How to have Multiple Plots on Same Figure

Introduction

Matplotlib is a powerful data visualization library in Python that allows you to create different types of plots such as line, scatter, bar, histogram, and more. One of the useful features of Matplotlib is the ability to have multiple plots on the same figure.

Having multiple plots on the same figure can be helpful when you want to compare different data sets or visualize different aspects of the same data set. In this tutorial, we will explore various ways to create multiple plots on the same figure using Matplotlib.

Before we dive into creating multiple plots on the same figure, let’s first understand some basic concepts of Matplotlib.


import matplotlib.pyplot as plt

The above code imports the pyplot module from Matplotlib, which provides a convenient interface for creating figures, subplots, and plotting functions. We can use this module to create and customize our plots.


import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1)
plt.plot(x, y2)

plt.show()

The above code creates two subplots on the same figure using `plt.plot()` function. The `x` array is created using `np.linspace()` function which returns evenly spaced numbers over a specified interval. The `y1` and `y2` arrays are created using `np.sin()` and `np.cos()` functions respectively. Finally, we use `plt.plot()` function to plot both arrays on the same figure and display it using `plt.show()` function.

In the next section, we will explore different ways to create multiple plots on the same figure using Matplotlib.

Table of Contents

  • Introduction
  • Creating Multiple Plots with Matplotlib
  • Subplots
  • Adjusting Subplot Layouts
  • Sharing Axes
  • Conclusion

Subplots

In Matplotlib, subplots are a way to have multiple plots on the same figure. Subplots can be arranged in different configurations depending on your needs. The `plt.subplots()` function is used to create subplots.

The basic syntax for creating subplots is as follows:


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

where `nrows` and `ncols` are the number of rows and columns of the subplot grid, respectively. The function returns two objects: `fig`, which represents the entire figure, and `ax`, which is an array of axes objects.

For example, let’s create a 2×2 subplot grid:


import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=2, ncols=2)

This will create a figure with four subplots arranged in a 2×2 grid. We can access each individual subplot by indexing into the `ax` array:


ax[0, 0].plot([1, 2, 3], [4, 5, 6])
ax[0, 1].scatter([1, 2, 3], [4, 5, 6])
ax[1, 0].bar([1, 2, 3], [4, 5, 6])
ax[1, 1].hist([1, 2, 3], bins=3)

In this example code block above we have plotted lines in the first subplot (top left), scatter plot in the second subplot (top right), bar chart in the third subplot (bottom left), and histogram in the fourth subplot (bottom right).

Each subplot can be customized independently by calling methods on its corresponding `ax` object. For example:


ax[0, 0].set_title('Line Plot')
ax[0, 1].set_title('Scatter Plot')
ax[1, 0].set_title('Bar Chart')
ax[1, 1].set_title('Histogram')

This will set the title of each subplot to the specified text.

In summary, subplots are a powerful tool for visualizing multiple plots on the same figure. By using the `plt.subplots()` function and indexing into the resulting `ax` array, you can create and customize subplots to fit your needs.

Adjusting Subplot Layouts

When creating multiple plots on the same figure using Matplotlib, it’s important to adjust the layout of the subplots so they don’t overlap or appear too close together.

Matplotlib provides a few different ways to adjust subplot layouts. One way is to use the `subplots_adjust()` function, which allows you to adjust the spacing between subplots using parameters such as `left`, `right`, `bottom`, and `top`. These parameters take values between 0 and 1, with 0 being the edge of the figure and 1 being the center.

Here’s an example:


import matplotlib.pyplot as plt

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

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

# Adjust the spacing between subplots
plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top=0.9, hspace=0.4)

# Show the plot
plt.show()

In this example, we create two subplots using the `subplots()` function and plot some data on each subplot. We then use `subplots_adjust()` to adjust the spacing between subplots. The `hspace` parameter controls the vertical spacing between subplots.

Another way to adjust subplot layouts is to use the `GridSpec` class in Matplotlib. This allows you to create a grid of subplots with custom widths and heights for each row and column.

Here’s an example:


import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# Create a grid of subplots with custom widths and heights
gs = GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[4, 1])

# Create the subplots
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, :])

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

# Show the plot
plt.show()

In this example, we create a grid of subplots with two rows and two columns using `GridSpec()`. We also specify custom widths and heights for each row and column using the `width_ratios` and `height_ratios` parameters. We then create the subplots using `subplot()` and plot some data on each subplot.

Adjusting subplot layouts is essential when creating multiple plots on the same figure using Matplotlib. With the `subplots_adjust()` function or the `GridSpec` class, you can customize the spacing between subplots to create an aesthetically pleasing visualization.

Sharing Axes

When creating multiple plots on the same figure in Matplotlib, it is common to want to share the x or y axis between the subplots. This can be done using the `sharex` and `sharey` parameters in the `subplots()` function.

For example, let’s say we have two subplots that share the x-axis:


import matplotlib.pyplot as plt

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

# Plot on first subplot
ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_ylabel('Subplot 1')

# Plot on second subplot
ax2.plot([1, 2, 3], [7, 8, 9])
ax2.set_ylabel('Subplot 2')

# Set x-axis label for bottom subplot only
ax2.set_xlabel('X Label')

plt.show()

In this example, we create two subplots vertically stacked on top of each other using `subplots(2, 1)`. We set `sharex=True` to indicate that both subplots should share the x-axis. We then plot different data on each subplot and label them accordingly.

Note how only the bottom subplot has an x-axis label since it is shared with the top subplot.

Similarly, we can use `sharey=True` to share the y-axis between subplots.


import matplotlib.pyplot as plt

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

# Plot on first subplot
ax1.plot([4, 5, 6], [1, 2, 3])
ax1.set_xlabel('Subplot 1')

# Plot on second subplot
ax2.plot([7, 8 ,9], [1 ,2, 3])
ax2.set_xlabel('Subplot 2')

# Set y-axis label for left subplot only
ax1.set_ylabel('Y Label')

plt.show()

In this example, we create two subplots side-by-side using `subplots(1, 2)`. We set `sharey=True` to indicate that both subplots should share the y-axis. We then plot different data on each subplot and label them accordingly.

Note how only the left subplot has a y-axis label since it is shared with the right subplot.

Conclusion

In this tutorial, we have learned how to create multiple plots on the same figure using Matplotlib. We started by importing the necessary libraries and creating the data for our plots.

We then explored different ways of creating subplots using the `subplot()` method and the `add_subplot()` method. We also learned how to adjust the spacing between subplots using the `subplots_adjust()` method.

Next, we looked at creating multiple plots on a single axis using the `plot()` method and its various parameters such as `label`, `color`, and `linestyle`. We also learned how to add a legend to our plots using the `legend()` method.

Finally, we explored how to create multiple plots with different y-axes using the `twinx()` and `twiny()` methods. This allowed us to plot two datasets with different units or scales on the same figure.

With these techniques, you can now create complex visualizations with multiple plots and axes in a single figure. Matplotlib is a powerful tool for data visualization, and understanding its capabilities will allow you to create informative and visually appealing plots for your data analysis projects.
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 […]