Wednesday, December 25, 2024
Google search engine
HomeLanguagesMatplotlib.pyplot.subplots() in Python

Matplotlib.pyplot.subplots() in Python

Matplotlib is a library in Python and it is a numerical-mathematical extension for the NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. 

Example:

Here is an example of a simple Python code to plot a graph using the Matplotlib library.

Python3




# sample code
import matplotlib.pyplot as plt
   
plt.plot([1, 2, 3, 4], [16, 4, 1, 8])
plt.show()


Output: 

Simple plot using Python matplotlib

Plot using Python matplotlib

Matplotlib subplots() Syntax

The subplots() function in the Pyplot module of the Matplotlib library is used to create a figure and a set of subplots.

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

Parameters: This method accept the following parameters that are described below:

  • nrows, ncols : These parameter are the number of rows/columns of the subplot grid.
  • sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes.
  • squeeze : This parameter is an optional parameter and it contains boolean value with default as True.
  • num: This parameter is the pyplot.figure keyword that sets the figure number or label.
  • subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot.
  • gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.

Returns: This method return the following values.

  • fig : This method return the figure layout.
  • ax : This method return the axes.Axes object or array of Axes objects.

Simple subplot

In this example, we will create a simple plot using the subplots() function in matplotlib.pyplot.

Python3




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
 
# First create some toy data:
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x**2)
 
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
 
fig.suptitle('matplotlib.pyplot.subplots() Example')
plt.show()


Output: 

matplotlib.pyplot.subplots() function example

matplotlib.pyplot.subplots() function example

Displaying multiple plots using subplots()

Matplotlib subplots() function let us plot multiple plots using the same data or the axis. Let us see a few examples for a better understanding.

Stacking Subplots in One Direction

In this example, we will plot two plots that share the y-axis. The nrows and ncols parameters are set to 1 and 2 respectively, which means the plot will have 1 row and 2 columns or 2 subplots. We can access these subplots using the index [0] and [1].

Python3




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
 
# First create some toy data:
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x)
y2 = np.sin(x**2)
 
# create 2 subplots
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].plot(x, y1)
ax[1].plot(x, y2)
 
# plot 2 subplots
ax[0].set_title('Simple plot with sin(x)')
ax[1].set_title('Simple plot with sin(x**2)')
 
fig.suptitle('Stacked subplots in one direction')
plt.show()


Output:

Stacking subplots in one direction

Stacking subplots in one direction

Stacking Subplots in Two Directions

This example is similar to the previous one. The only difference is that we provided the values of nrows and ncols to 2. This means that the plot is divided into 2 rows and 2 columns which gives us a total of 4 subplots. We can access these plots using the index.

Python3




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
 
# First create some toy data:
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x)
y2 = np.sin(x**2)
y3 = y1**2
y4 = y2**2
 
fig, ax = plt.subplots(nrows=2, ncols=2)
ax[0, 0].plot(x, y1, c='red')
ax[0, 1].plot(x, y2, c='red')
ax[1, 0].plot(x, y3, c='blue')
ax[1, 1].plot(x, y3, c='blue')
 
ax[0, 0].set_title('Simple plot with sin(x)')
ax[0, 1].set_title('Simple plot with sin(x**2)')
ax[1, 0].set_title('Simple plot with sin(x)**2')
ax[1, 1].set_title('Simple plot with sin(x**2)**2')
 
fig.suptitle('Stacked subplots in two direction')
plt.show()


Output:

Stacking subplots in two directions

Stacking subplots in two directions

Sharing Axis

In this example, we will plot the graphs that share the same axis. We will create plots that will share the y-axis and the label but will have their own x-axis and label. This can be done by passing a value to the ‘num’ parameter of the subplot() function. The ‘sharex’ parameter is set to True, which means the plots created will share X-axis among them.

Python3




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
 
# First create some toy data:
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x)
y2 = np.sin(x**2)
 
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.plot(x, y1, c='red')
ax2.plot(x, y2, c='red')
 
ax1.set_ylabel('Simple plot with sin(x)')
ax2.set_ylabel('Simple plot with sin(x**2)')
 
fig.suptitle('Subplots with shared axis')
plt.show()


Output:

Subplots with shared axis

Subplots with shared axis

Polar Axis

In this example, we will plot the graphs using the polar coordinates. The subplot_kw parameter of the subplot() function is given a dictionary value of projection set to ‘polar’ which tells the subplot() function to create a polar graph.

Python3




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
 
# First create some toy data:
x = np.linspace(0, 1.5 * np.pi, 100)
y = np.sin(x**2)+np.cos(x**2)
 
fig, axs = plt.subplots(nrows=2, ncols=2,
                        subplot_kw = dict(polar = True))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
 
fig.suptitle('matplotlib.pyplot.subplots() Example')
plt.show()


Output:

matplotlib.pyplot.subplots() function example

matplotlib.pyplot.subplots() function example

RELATED ARTICLES

Most Popular

Recent Comments