Matplotlib gridspec: Detailed Illustration

Hello, coders!! In this article, we will be learning about matplotlib gridspec. We will see some examples to grasp a clear concept on the mentioned topic. Without any further ado, let us get straight into the topic.

What is matplotlib gridspec?

The matplotlib.gridspec.GridSpec class is used to specify the grid’s geometry to place a subplot. We need to set the number of rows and columns of the grid.

Syntax:

class matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None)

Parameters:

  • nrows: number of rows in the grid
  • ncols: number of columns in the grid
  • figure: to draw figures
  • left, right, top, bottom:  to define the extent of the subplots as a fraction of figure width or height
  • wspase: to reserve the width space between subplots
  • hspace: to reserve the height space between subplots
  • width_ratios: represents the width ratios of the columns
  • height_ratios: represents the width ratios of the rows

Methods in the class of matplotlib gridspec:

get_subplot_params(self, figure=None):

This function returns a dictionary of subplot layout parameters.

tight_layout(self, figure, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): 

It is used to give specific padding to adjust the subplots.

Illustrated Examples for Matplotlib girdspec:

Let us now see some examples for a clearer concept.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig, axes = plt.subplots(ncols=3, nrows=3, constrained_layout=True)
Illustrated Examples for Matplotlib girdspec
Output

In this example, we have not used matplotlib gridspec. We have created subplots with 3×3 dimensions of the figure. We will now create the same figure using gridspec.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(constrained_layout=True)
spec = gridspec.GridSpec(ncols=3, nrows=3, figure=fig)
ax1 = fig.add_subplot(spec[0, 0])
ax2 = fig.add_subplot(spec[0, 1])
ax3 = fig.add_subplot(spec[0, 2])
ax4 = fig.add_subplot(spec[1, 0])
ax5 = fig.add_subplot(spec[1, 1])
ax6 = fig.add_subplot(spec[1, 2])
ax7 = fig.add_subplot(spec[2, 0])
ax8 = fig.add_subplot(spec[2, 1])
ax9 = fig.add_subplot(spec[2, 2])
matplotlib gridspec to achieve
Output

As you can see, here we have created the same figure. However, we have used matplotlib gridspec to achieve the desired result. We have defined the grid size as 3×3. We then defined the 9 subplots in different axes to obtain the figure shown above.

This was just a simple example to see how gridspec works. It is primarily used when we create subplots that span rows and columns.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(gs[0, :1])
ax2 = fig.add_subplot(gs[1, :-1])
ax3 = fig.add_subplot(gs[1:, -1])
ax4 = fig.add_subplot(gs[-1, -2])

how gridspec works
Output

As you can see, we have customized the layout as per our preference and added a few subplots that span rows and columns to our figure.

GridSpec using SubplotSpec:

This is used to specify the location of a subplot in a gridspec.

Syntax:

matplotlib.gridspec.SubplotSpec(gridspec, num1, num2=None)

Parameters:

  • gridspec: The GridSpec, which the subplot is referencing.
  • num1, num2:
    • The subplot will occupy the num1-th cell of the given gridspec.
    • If num2 is provided, the subplot will span between the num1-th and num2-th cell inclusive.
matplotlib GridSpec using SubplotSpec
Output

We have customized our figure’s layout using subplotspec() in this example. The parameter of this function identifies the axis of the given subplot.

Matplotlib gridspec shared axes:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig, axes = plt.subplots(ncols=3, sharey=True)

fig.suptitle('Shared y-axis', size=20)

fig.tight_layout()


plt.show()
Matplotlib gridspec shared axes
Output

In this example, we have set the ‘sharey’ parameter as ‘True.’ As a result, in the figure, the plots share the y-axis and then use the tight_layout() method to give specific padding to adjust the subplots.

Matplotlib gridspec imshow:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(15,15)
fig, axes = plt.subplots(3, 2)

axes[0, 0].imshow(data)
axes[1, 0].imshow(data)
axes[2, 0].imshow(data)


axes[0, 1].imshow(data)
axes[1, 1].imshow(data)
axes[2, 1].imshow(data)

plt.setp(axes, xticks=[], yticks=[])
plt.show()
imshow
Output

As you can see, in this example, we have used the imshow() method to display the images at different axes. We use the random.rand() method to create a 15×15 matrix of random value. Lastly, we use the imshow() method to display the images at different axes.

Matplotlib gridspec ratio:

There are two parameters available for this:

  • width_ratios : Width ratios of the columns
  • height_ratios : Height ratios of the rows
fig = plt.figure(constrained_layout=True)
widths = [1, 2, 3]
heights = [1, 2, 3]
spec = fig.add_gridspec(ncols=3, nrows=3, width_ratios=widths,
                          height_ratios=heights)
for row in range(3):
    for col in range(3):
        ax = fig.add_subplot(spec[row, col])

        label = 'Width: {}\nHeight: {}'.format(widths[col], heights[row])
        ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')
Matplotlib gridspec ratio
Output

In this example, we used the width_ratios and height_ratios parameters to specify the height and width of the various subplots in the figure.

Conclusion: Matplotlib Gridspec

With this, we come to an end with this article. I hope that the concept of gridspec was cleared from this article.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments