How to Customize Multiple Subplots in Matplotlib

This article will cover a specific issue that most Python users encounter when using Matplotlib for plotting their graphs. I am talking about defining multiple subplots and being able to access and change their properties individually.

In the following sections, we will see how to use the Matplotlib function .subplots() for generating multiple subplots and how to define properties like the labels of the axes, the title, and the grid of each of them both separately and simultaneously.

I explained this article in the following video tutorial:

Importing Libraries

Since we will just create some subplots and modify some of their properties, the only library that will be used throughout the entire example is Matplotlib; more specifically, we import the Matplotlib.pyplot package to be able to plot and modify our plotting windows.

import matplotlib.pyplot as plt

Creating the Plotting Window and Defining the Subplots

The first step towards the creation of a Matplotlib plot is the definition of a plotting window, i.e. the window that will be displayed after running the code and that will contain all the subsequently defined plots. To do this, we use the matplotlib function .figure() and we assign its value to the variable “fig”. We do not specify any input parameter; however, it is possible to modify the size of the figure, its color, and some other properties; you can find the official documentation at this link.

fig = plt.figure()

Once created the plotting window, we have to define the subplots; this can be done by using the function .subplots(), applied to the previously defined figure (i.e. the variable “fig”). If we do not pass any input parameter, this function will generate a single subplot while if we want it to display multiple subplots, we have to specify the number of rows and columns in which we want to divide the plotting window. These input parameters are called “nrows” and ”ncols”; however, we can directly address them by simply typing the two respective numbers.

Other useful parameters are sharex and sharey, if we put them equal to True, the generated subplots will share the x and/or the y axes. For this example, we define four subplots, displayed along two rows and two columns; and we assign them to the variable “ax”. The following code line describes the procedure. We also use the function .subplots_adjust() for changing the separation between the four subplots, specifically by setting to 0.5 the value of the parameters hspace and wspace (corresponding to the vertical and horizontal separation, respectively).

ax = fig.subplots(2, 2)
fig.subplots_adjust(hspace=0.5, wspace=0.5)

The obtained result is displayed in Figure 1, which shows the four subplots initialized in a 2×2 grid inside the matplotlib window.

Figure 1: Initialization of four subplots, distributed in a 2×2 grid within the matplotlib window.

Changing the Properties of Individual Subplots

Now that we created our four subplots, we proceed further and change some of the properties of individual plots. This is a really easy task; indeed, thanks to the strategy that we adopted for the definition of the subplots, now the variable “ax” is a 2×2 array and hence allows accessing each of its elements (each subplot) by simple indexing.

In our case, the subplot on the upper left corner is the element [0, 0], the one in the upper right corner the [0, 1], on the bottom left we have the [1, 0] and on the bottom right the [1, 1]. We can now try to add a title to the subplot in the bottom left corner, this can be done by applying the method .set_title() to the element ax[1, 0] and by passing as a string the title that we want to add:

ax[1, 0].set_title('Plot n° 3')

The final result is displayed in Figure 2; as you can see, we added a title solely to the bottom left subplot, while the others are still lacking it.

Figure 2: By applying the method .set_title() to the [1, 0] element of the ax array, we added a title solely to the subplot in the bottom left corner.

In an analogous way, we can access and change the properties of all the others individual subplots that make up our figure. To this purpose, some of the most frequently used methods are:

  • .grid() for enabling the grid on your plot and for changing its properties (like color and linewidth)
  • .set_xlabel or set_ylabel() for setting the title of the x and y axes, respectively
  • .set_facecolor() for changing the background color of each subplot

Automatically Setting the Properties of All Subplots

Let’s now suppose that we want to initialize some of the previously listed properties for all of the subplots present in our window. Even if it was not a difficult task, repeating that step for multiple properties and for multiple plots could be repetitive and time consuming (as well as annoying).

To solve this issue, it is possible to exploit for loops for defining and/or changing some of the properties of all the subplots automatically and rapidly. Indeed, since the variable ax has been initialized as a 2×2 array, we can hence use two nested for loops for accessing each subplot one at a time and changing all its properties in an iterative fashion. In the following code lines, we will use two nested for loops for accessing each of the subplots and changing properties like the title, the grid, the background color and the axes labels.

Before entering the for loops, we define the variables “rows” and “cols” which indicates the total number of rows and columns the window is divided into; they will be then used as escape value for stopping the iterations inside the loops. We also define an index “n”, which will be used for assigning the number to each plot title.

rows, cols = 2, 2
n = 1
for i in range(rows):
    for j in range(cols):
        ax[i, j].grid(color='w', linewidth=1)
        ax[i, j].set_ylabel('Y axis')
        ax[i, j].set_xlabel('X axis')
        ax[i, j].set_facecolor("grey")
        ax[i, j].set_title('Plot n° ' + str(n))
        n += 1
plt.show()

As you can see from the code lines, each of the subplots will have a white grid, two labels for the y and x axis, respectively, a grey background and a title stating “Plot n° (number of the plot)”, where the number of the plot is dictated by the value of the index “n”. The final result is displayed in Figure 3.

Figure 3: Using two nested for loops we were able to change the properties of all the four subplots automatically, without the need of repeating all the steps for each of them.

Full Code

Here’s the full code from this tutorial:

import matplotlib.pyplot as plt

fig = plt.figure()
rows, cols = 2, 2
ax = fig.subplots(nrows=rows, ncols=cols)
fig.subplots_adjust(hspace=0.5, wspace=0.5)
# adding a title to an individual subplot
ax[1, 0].set_title('Plot n° 3')
# automatically set the properties for all the subplots
n = 1
for i in range(rows):
    for j in range(cols):
        ax[i, j].grid(color='w', linewidth=1)
        ax[i, j].set_ylabel('Y axis')
        ax[i, j].set_xlabel('X axis')
        ax[i, j].set_facecolor('grey')
        ax[i, j].set_title('Plot n° ' + str(n))
        n += 1
plt.show()

Conclusions

In this article we saw how to access every single subplot present in a matplotlib window; in the first part we manually added a title to just one of the four subplots, in the second part we exploited two nested for loops to iterate through all the subplots and changing all of their properties simultaneously and automatically.