matplotlib create multiple plots

How to Create Multiple Matplotlib Plots in One Figure?

In this tutorial, we’ll try to understand how to create multiple matplotlib plots in one figure with the help of some examples.

To create multiple plots in a single figure in matplotlib, you can use the matplotlib.pyplot.subplots() function. This creates a grid of subplots in a single figure with each subplot represented by a different Axes object.

Using the matplotlib.pyplot.subplots() function

Use pyplot.subplots function to create multiple subplots within the same figure. Pass the details like the number of rows and the columns you want in the grid of subplots. It returns the figure object and an array of Axes objects for the subplots.

The following is the syntax –

Basic Syntax:

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, **fig_kw)

Parameters:

  • nrows, ncols: Number of rows/columns of the subplot grid.

For more details on the parameters, refer this.

Return:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

  • fig: Figure – the top-level container for all the plot components (in this case, the top-level container of the subplot grid.
  • axes: Axes object or array of Axes object depending upon how many subplots you’re creating in the grid.

Let’s now look at some examples of creating a grid of subplots using the above syntax –

Example 1 – Plot subplots horizontally

If you want all the subplots to be horizontally aligned, create a subplot grid with only one row. For example, let’s create two subplots on a single row.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)

#creating subplots with only 1 row and 2 columns
fig,axes = plt.subplots(nrows=1,ncols=2)

#plotting each subplot
axes[0].plot(x,y1)
axes[1].plot(x,y2)

Output:

horizontal subplots in a figure

You can see that the resulting figure has the subplots aligned horizontally on a single row.

In the above example, we –

  1. Import the required modules.
  2. Define the values for x using the numpy.linspace function (refer this), and some random values for y1 & y2 using numpy.random.rand (refer this).
  3. Create a grid of subplots with 1 row and 2 columns using matplotlib.pyplot.subplots().
  4. Plot the x and y1 on the first subplot and x and y2 on the second subplot using the respective Axes object obtained in step 3.

Example 2 – Plot subplots vertically

Similarly, you can align the subplots vertically by creating a grid of subplots with only one column. Let’s take the same example as above but this time create a vertical grid of subplots.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)

#creating subplots with only 2 rows and 1 column
fig,axes = plt.subplots(nrows=2,ncols=1)

#plotting each subplot
axes[0].plot(x,y1)
axes[1].plot(x,y2)

Output:

vertical subplots in a figure

In the above example, we –

  1. Import the required modules.
  2. Define the values for x using the numpy.linspace function (refer this), and some random values for y1 & y2 using numpy.random.rand (refer this).
  3. Create a grid of subplots with 2 rows and 1 column using matplotlib.pyplot.subplots(). This results in a vertical grid.
  4. Plot the x and y1 on the first subplot and x and y2 on the second subplot using the respective Axes object obtained in step 3.

Example 3 – Create a grid of plots

We can also create a custom grid of subplots, for example – a 2×2 grid of the subplots.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

#creating subplots with only 2 rows and 2 columns
fig,axes = plt.subplots(nrows=2,ncols=2)

#plotting each subplot
axes[0][0].plot(x,y1)
axes[0][1].plot(x,y2)
axes[1][0].plot(x,y3)
axes[1][1].plot(x,y4)

Output:

subplots in a 2x2 grid

In the above example, we –

  1. Import the required modules.
  2. Define the values for x using the numpy.linspace function (refer this), and some random values for y1, y2, y3, and y4 using numpy.random.rand (refer this).
  3. Create a 2×2 grid of subplots with 2 rows and 2 columns using matplotlib.pyplot.subplots().
  4. Plot each of the four y variables on different subplots.

Example 4 – Add customizations to the subplots

Each subplot is a separate Axes object and you can use this Axes object to customize the subplot. For example, let’s change the line style for each of the subplots in the 2×2 grid.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

#creating subplots with only 2 rows and 2 columns
fig,axes = plt.subplots(nrows=2,ncols=2)

#plotting each subplot
axes[0][0].plot(x,y1,'-')
axes[0][1].plot(x,y2,'r--o')
axes[1][0].plot(x,y3,'g--o')
axes[1][1].plot(x,y4,'b--o')

Output:

subplots in grid with custom titles

You can see that the subplots are styled differently.

We can similarly add titles to each subplot using the respective Axes object’s set_title() function.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

#creating subplots with only 2 rows and 2 columns
fig,axes = plt.subplots(nrows=2,ncols=2)

#plotting each subplot with custom title
axes[0][0].plot(x,y1,'-')
axes[0][0].set_title('Plot-1')
axes[0][1].plot(x,y2,'r--o')
axes[0][1].set_title('Plot-2')
axes[1][0].plot(x,y3,'g--o')
axes[1][0].set_title('Plot-3')
axes[1][1].plot(x,y4,'b--o')
axes[1][1].set_title('Plot-4')

Output:

Example 6 – Remove overlap between subplots with tight_layout()

You can use the matplotlib.pyplot.tight_layout() function to remove the overlap between the Axes object. It attempts to resize the subplots such that there’s no overlap between them.

Let’s apply this to the above plot which has some overlap.

import matplotlib.pyplot as plt
import numpy as np

#defining x, y1, y2 values
x = np.linspace(0,10,10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

#creating subplots with only 2 rows and 2 columns
fig,axes = plt.subplots(nrows=2,ncols=2)

#plotting each subplot with custom title
axes[0][0].plot(x,y1,'-')
axes[0][0].set_title("Plot-1")
axes[0][1].plot(x,y2,'r--o')
axes[0][1].set_title("Plot-2")
axes[1][0].plot(x,y3,'g--o')
axes[1][0].set_title("Plot-3")
axes[1][1].plot(x,y4,'b--o')
axes[1][1].set_title("Plot-4")
plt.tight_layout()

Output:

subplots in tight layout

The subplots now do not have any overlap and are more readable.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Chaitanya Betha

    I'm an undergrad student at IIT Madras interested in exploring new technologies. I have worked on various projects related to Data science, Machine learning & Neural Networks, including image classification using Convolutional Neural Networks, Stock prediction using Recurrent Neural Networks, and many more machine learning model training. I write blog articles in which I would try to provide a complete guide on a particular topic and try to cover as many different examples as possible with all the edge cases to understand the topic better and have a complete glance over the topic.

Scroll to Top