Matplotlib Subplot in Python

Matplotlib Subplot in Python

Data is one of the most valuable commodities in the world today. Billions of data points are generated daily, but raw data alone is useless. Data scientists and analysts process, clean, and extract key features from this data, fitting it into models to make it meaningful. This processed data then plays a crucial role in decision-making. However, large tables filled with numbers can be difficult to interpret, especially for individuals who lack technical expertise but are key stakeholders in important decisions. This is where data visualization becomes essential. It simplifies complex data and presents it clearly and understandably. One of the most valuable features of data visualization is multiple subplots. This article will explore what are multiple subplots, why they are helpful, and how to implement them in Python.

Table of Contents:

A subplot is a smaller plot that exists within a larger plot. In technical terms, a subplot is a collection of axes that share the same figure in Matplotlib. The figure below illustrates a single subplot.

Single Subplot

When we include multiple subplots within the same figure, it is referred to as multiple subplots. This technique allows us to visualize different datasets or perspectives within a single visualization space. The figure below demonstrates the concept of multiple subplots

Multiple Subplots

Before diving deeper, let us first understand Figures and Axes in Matplotlib.

Advance Your Career with Python – Start Learning Now!!
Join thousands of learners building in-demand skills.
quiz-icon

Figures and Axes in Matplotlib

In Matplotlib, the Axes and Figure objects are the backbone of any data visualization. Knowing how they work is essential, and learning them from an object-oriented programming (OOP) standpoint will help you better understand and visualize the concept.

A Figure is like a container for a visualization. Consider it to be the canvas upon which your plots, legends, labels, and other graph-related items are kept. From an OOP point of view, a Figure object encapsulates many plots and is the parent object responsible for keeping them in order.

Inside a Figure, we have one or more Axes objects. An Axes is one plot and comprises everything to do with the particular plot, including the x-axis, y-axis, title, labels, and data visualization. Each Axes instance is an independent child object within the Figure, which allows you to have multiple subplots in a single figure.

If the figure contains one plot only, the Axes object is a singleton; if more than one subplot is there, then the Axes object is a Python list of axes containing references to various axes objects.

Example:

Python

Output:

Fig and Axes Output

Explanation: Here, we plotted a single subplot in the same figure and multiple subplots in the same figure. The output contains the memory location of all these subplot objects along with the graph figures shown below.

Fig and Axes - Single Subplot
Fig and Axes - Multiple Subplot

Why use Multiple Subplots?

Here are some key reasons why individual plots were not sufficient in data visualization, which resulted in the concept of subplots. 

  • Subplots can be especially useful for visualizing high-dimensional data. By keeping low-dimensional summaries side by side, they disclose local patterns but keep a global context.
  • Subplots enable you to represent different things about a single dataset in one layout. For instance, you can have distributions represented with histograms, relationships with scatter plots, and trends using line charts, all in one figure.
  • Subplots simplify the presentation of trends in data by combining several plots into a single figure. This eliminates the need to switch between different figures, helping maintain focus on the overall data story. 
  • They give a structured and orderly visualization arrangement suitable for reports and presentations. By systematically arranging plots, subplots promote clarity and professionalism.

Implementation of Multiple Subplots using Matplotlib

Matplotlib is a data visualization package in Python. It is used to plot and visualize various graphs such as Line graphs, histograms, bar graphs, and many more. Matplotlib allows you to plot multiple plots in the same figure. It has two functions or methods, subplot() and subplots(), that allow you to implement multiple plots. Even though the methods sound similar, they follow fundamentally different programming paradigms

  1. fig.add_axes()
  2. plt.subplot()
  3. plt.subplots() 
  4. GridSpec()

Let us explore the features and use cases for each of these in the coming sections.

Using fig.axes() Method from PyPlot Module of Matplotlib

Matplotlib provides a lower-level function called add_axes() for precise and absolute placement of axes (subplots) inside a figure. It is useful when you need pixel-perfect subplot placement. It is also recommended when you want to manually control subplot positions.

The general syntax for using this function is

fig.add_axes([left, bottom, width, height])

This list of values represents the percentage of the figure dimensions. For Example: [0.2, 0.5, 0.4, 0.3] means 20% from the left, 50% from the bottom, and takes up 40% width and 30% height.

Each of these values in the list takes a float value ranging from 0 to 1. 

  • Each of these values in the list takes a float value ranging from 0 to 1. 
  • This list of values represents the percentage of the figure dimensions. For Example: [0.2, 0.5, 0.4, 0.3] means 20% from the left, 50% from the bottom, and takes up 40% width and 30% height.

For Example:

Python

Output:

fig.axes function

Using plt.subplot() Method from PyPlot Module of Matplotlib

The plt.sublplot() method is present in the pyplot module of the Matplotlib package. This method is state-based. This means that each time you call plt.subplot(), you are telling matplotlib to change the current “active” axes. The plt commands will be implemented on the current “active” axes until plt.subplot() is called again and the “active” axes change again. You manually define each subplot one by one, referencing it by its grid index.

The general syntax for this function is

plt.subplot(nrows, ncols, index)

When to use: This method is useful when you are manually plotting out a few subplots and want explicit control over the order in which they are stacked in the figure.

Example of horizontally stacked plots:

Python

Output:

plt.subplot method - horizontal stack

Example: Here, using the plt.subplot() function, we plotted the subplots in a horizontal layout. We plot the graph by accessing the axes one by one.

Example of vertically stacked plots:

Python

Output:

plt.subplot method - vertical stack

Explanation:  Here, using the plt.subplot() function, we plotted the subplots in a vertical layout. We plot the graph by accessing the axes one by one.

Get 100% Hike!

Master Most in Demand Skills Now!

Using plt.subplots() Method from PyPlot Module of Matplotlib

The plt.subplots() method is also present in the PyPlot module of the Matplotlib package. This method is also referred to as automatic subplot creation. It returns a tuple, (fig, ax), containing a figure object fig and ax, which is a list of many axes objects. You can store these and interact with them directly. It promotes better structure and maintainability of your code, especially for complex visualizations. 

The general syntax for the following function is

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

When to use: If you need to access or update plots after creating them, plt.subplots() is usually preferred since it returns Figure and Axes objects. This function gives you more control and flexibility.

Example:

Python
plt.subplots method output

Explanation: Here, we have plotted the subplots using the plt.subplots() function. Since ‘axes’ is a list of subplots, accessing the subplots is easier using an index.

Using Gridspec() for Advanced Layout

GridSpec is a class from the matplotlib.gridspec module. It creates a flexible grid layout and gives you precise control over subplot placement within a grid. It is especially powerful for non-uniform or asymmetric layouts, which are hard to achieve with plt.subplot() or plt.subplots() alone. Here are a few reasons to choose GridSpec() over the plt.subplot() or plt.subplots() methods: 

  • Unequal subplot sizes
  • Irregular subplot positions
  • Shared axes in custom configurations

With GridSpec, you can create complex dashboards where subplots span over multiple rows or columns and align the axes correctly.

The general syntax is

from matplotlib.gridspec import GridSpec
gs = GridSpec(nrows, ncols)

Example:

Python

Output:

Gridspec method output

Explanation: Here, using the gripspec() function, we had more flexibility in the layout and space occupancy of the subplots.

Customizing Subplots in Matplotlib

The next step after creating the subplots is customizing them. Customization improves readability, visual appeal, and clarity. Below are some key ways to customize your subplots using Matplotlib.

Adding Titles, Labels and Legends

Each subplot is an individual Axes object, so you can add a title, x/y labels, and a legend to each one just like you would in a regular plot, or you can add a title to the figure all at once instead of giving titles to individual subplots. This helps the graph communicate its message. Here is a code demonstrating the same. 

Example:

Python

Output:

Customizing - adding titles, labels

Explanation: Here, we have customized both the plots individually, giving both of them custom colors based on their requirements. 

Adjusting Figure Size and Spacing

Sometimes, your titles, labels, and legends might overlap and make it difficult for the reader to read and hinder their understanding of the graph. To fix this, matplotlib offers 

  • plt.tight_layout() for convenience 
  • plt.subplots_adjust() for when you want more control over the adjustments.

The general syntax for plt.subplots_adjust() is 

plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.4, hspace=0.4)
  • wspace and hspace controls the width and height spacing between subplots.
  • left, right, top, and bottom define the spacing around the whole figure.

Sharing Axes Across Subplots

Sharing Axes helps you align subplots for better comparisons, especially when they share at least one common data scale. It avoids clutter by ensuring the axes do not repeat unnecessarily. 

Below are the arguments to make the subplots share axes.

  • sharex=True: Both subplots share the same X-axis scale
  • sharey=True: Both share the Y-axis scale (useful in side-by-side plots)

When should you share axes?

  • Whenever you are comparing similar data across different timeframes or categories. 
  • When you want to highlight the difference in the trends without confusing the reader with different scales.
  • When you want to save space and avoid duplicate axis ticks and labels.

Example: 

Python

Output:

Customizing - sharing axes

Common Mistakes While Plotting Multiple Subplots

As a beginner, when you are working with multiple subplots in Matplotlib, it is easy to make mistakes. Matplotlib is a Data Visualization Module. Debugging these errors can be frustrating as they are unexpected and rarely due to wrong logic. Here are some of the most frequent ones along with their solutions.

Overlapping Plots and Labels

Issue:
The most common issue that you will ever face is the issue of overlapping plots and labels. It is also the one that takes priority in debugging and must be fixed first. This is because overlapping makes the graph confusing and the visualization unreadable, defeating the purpose of having a graph.

Fix:
You can use layout management to auto-adjust spacing or plt.tight_layout() just before using the plt.show() command.

The general syntax for the following is

plt.tight_layout()
# or
fig, ax = plt.subplots(constrained_layout=True)

Incorrect Subplot Indexing

Issue:
If you get IndexError: index out of range or unexpected plot positions error when running your code, it is most likely because you used the wrong index. 

Fix:

The index for axes in Matplotlib starts from 1 and not 0 like other Python data types. Make sure you have given the correct index in the code.

Not Flattening the Axes Array

Issue:
When you use plt.subplots() with more than one row and column, the axes objects are returned in the form of a nested list instead of a basic list. You access the elements in a nested list using two indexes, like axs[0][1]. But in Matplotlib we use axs[1] to access the first plot, axs[2] to access the second plot, and so on. This throws an error.

Fix:

You flatten the axs list using plt.flatten so that axs[0][0] refers to axs[0], axs[0][1] refers to axs[1], and so on.

The general syntax is

fig, axs = plt.subplots(2, 2)
axs = axs.flatten()

Not Reusing the Code

Issue:

Whenever you are using multiple subplots, you likely have a lot of plots. You might have to customize the plots for a better understanding of the users. Usually, beginners manually set titles, labels, or styles for each subplot. Due to this, the code becomes messy and redundant.

Fix:
You should use loops and functions so that your code follows the DRY (Don’t Repeat Yourself) principle.

Practical Example

Let us implement a multiple subplot with a variety of plots like scatter plots, histograms, and many more.

Python

Output:

Practical Example Output

Alternatives to Matplotlib for Plotting Subplots

Other modules such as Seaborn, Plotly, and Altair allow you to plot multiple subplots in Python. While Matplotlib is powerful, other libraries offer different approaches to subplots. Below you can find a comparative table that will help you decide which module to use according to your use case. 

Feature Pros Cons
Matplotlib 1. Highly customizable
2. Huge community and support
1. Not interactive by default
Seaborn 1. Built on Matplotlib
2. Cleaner syntax and default styles
1. Less control than Matplotlib
2. Limited plot types
3. No native interactivity
Plotly 1. Fully interactive
2. Easy to use for web dashboards
1. Larger file size
2. Slightly heavier setup
Altair 1. Built-in interactivity
2. Great for data exploration
1. Not as flexible for custom plots
2. Struggles with large datasets
Kickstart Your Coding Journey with Python – 100% Free
Learn the basics of Python through hands-on practice and projects.
quiz-icon

Conclusion

Multiple subplots are an effective technique in data visualization, particularly when dealing with large, complex datasets or when comparison between visual objects is important. We have discussed the concept of subplots and learned how to apply them and when and how to do so through tools such as plt.subplot(), plt.subplots(), and GridSpec(). Whether you’re creating reports for stakeholders, dashboards for engagement, or performing deep data analysis, having control over subplots will make your visual narrative neater, more informative, and more impactful. By using the appropriate techniques and tools, you can turn raw data into powerful visuals that are easy to understand.

 To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

How to Create Multiple Subplots in Matplotlib – FAQs

Q1. Can there be multiple subplots?

Yes, there can be multiple subplots within a figure. You can do this using the functions plt.subplot(), plt.subplots(), and gridspec() in Matplotlib.

Q2. How do you plot multiple plots at once in Matplotlib?

You can use plt.subplot() or plt.subplots() to create multiple Axes and plot each individually.

Q3. What does subplot(3, 1, 1) mean?

The subplot(3, 1, 1) creates a 3-row, 1-column grid and targets the first subplot.

Q4. How do you plot multiple graphs on one graph?

You can use plt.subplots() to plot multiple graphs on one graph.

Q5. How do you combine multiple data into one graph?

You can plot all datasets on the same Axes using different colors, markers, or labels for distinction.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner