Matplotlib - Subplots() Function



In the context of data visualization, subplots refer to a layout within a single figure where multiple plots (or axes) are arranged in rows and columns. It is a common and useful task, especially when you want to display multiple plots within the same figure for analysing different aspects of data.

In Matplotlib, the subplots() function is a powerful tool for creating subplot layouts (means groups of axes) within a single figure.

Understanding subplots() Function

The subplots() function is a part of the Matplotlib library and is available in both matplotlib interfaces, the object-oriented approach (matplotlib.figure.Figure.subplots()) and the functional interface (matplotlib.pyplot.subplots()).

The matplotlib.figure.Figure.subplots() method is called on a Figure object and returns an Axes or array of Axes.

The matplotlib.pyplot.subplots() function is a wrapper for matplotlib.figure.Figure.subplots() and directly creates a figure object along with an axes or array of axes object.

Following is the syntax of the function −

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)

Here are the details of its parameters −

Both matplotlib.figure.Figure.subplots() and matplotlib.pyplot.subplots() accept several parameters to customize the subplot layout.

  • nrows, ncols: Number of rows and columns of the subplot grid.
  • sharex, sharey: Controls sharing of properties among x or y axes.
  • squeeze: Controls the squeezing of extra dimensions from the returned array of axes.
  • subplot_kw: Dictionary with keywords passed to the add_subplot call used to create each subplot.
  • gridspec_kw: Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
  • Additional keyword arguments are passed to the pyplot.figure() call.

Creating Subplots

Creating subplots is straightforward and can be achieved by simply calling the subplot() function. This will allows you to create a simple figure with only one subplot or to define a grid layout for multiple subplots within the same figure.

By specifying the number of rows and columns in the subplot grid, you can control the layout of the subplots.

Example

Here is an example that uses the matplotlib.pyplot.subplots() method to create a simple figure with only one subplot.

import matplotlib.pyplot as plt
import numpy as np
 
# First create sample data
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
plt.show()

Output

On executing the above code we will get the following output −

subplots_function_ex1

Example

Here is the object-oriented approach to create a simple figure with only one subplot.

import matplotlib.pyplot as plt
import numpy as np
 
# First create sample data
x = np.linspace(0, 2*np.pi, 400)
y = np.cos(x**2)

# Create a figure
fig = plt.figure()

# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
plt.show()

Output

On executing the above code we will get the following output −

subplots_function_ex2

Accessing Subplots

Subplots can be accessed by unpacking the output array immediately after creation or can be accessed by using indexing on the axes array.

Example

In this example, subplots are accessed through unpacking the output array immediately after creation.

import matplotlib.pyplot as plt
import numpy as np
 
# First create sample data
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create two subplots and unpack the output array immediately
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y)
ax2.scatter(x, y)
plt.suptitle('Two Subplots')
plt.show()

Output

On executing the above code we will get the following output −

subplots_function_ex3

Example

In this example subplots are access through index of the axes array. And legend is add to the each subplot.

import matplotlib.pyplot as plt
import numpy as np
 
# First create sample data
x = np.linspace(0, 2*np.pi, 400)
y = np.cos(x**2)

# Create a figure
fig = plt.figure()

# Create a subplot
axes = fig.subplots(2, 2)

axes[0, 0].plot(x, y, label='cos')
axes[0, 0].legend()
axes[0, 1].plot(np.exp(x), label='Exponential')
axes[0, 1].legend()
axes[1, 0].plot(np.log10(x), label='Log')
axes[1, 0].legend()
axes[1, 1].scatter(x, y, label='Scatter')
axes[1, 1].legend()
plt.show()

Output

On executing the above code we will get the following output −

subplots_function_ex4

Sharing Axes

The subplots() function also allows you to control the sharing of properties among x or y axes using the sharex and sharey parameters. This can be useful for ensuring consistency in axis scaling and tick labeling across subplots.

Example

This example demonstrates how to create a grid of subplots that share the same y-axis.

import matplotlib.pyplot as plt
import numpy as np
 
# First create sample data
x = np.arange(1, 5)

# Create a figure
fig = plt.figure()
plt.title('Sharing Axes')

# Create a subplot
axes = fig.subplots(2, 2, sharey=True)
axes[0, 0].plot(x,x*x)
axes[0, 1].plot(x,np.sqrt(x))
axes[1, 0].plot(x,np.exp(x))
axes[1, 1].plot(x,np.log10(x))
plt.show()

Output

On executing the above code we will get the following output −

subplots_function_ex5
Advertisements