Matplotlib subplot tutorial

In this Python tutorial, we will discuss matplotlib subplot in python, which lets us work with multiple plots in a figure and we will also cover the following topics:

  • Matplotlib subplot
  • Matplotlib subplot figure size
  • Matplotlib subplot title overall
  • Matplotlib subplot title for each plot
  • Matplotlib subplot title font size
  • Matplotlib subplot title bold
  • Matplotlib subplot title position
  • Matplotlib subplot title padding
  • Matplotlib subplot legend
  • Matplotlib subplot share axis
  • Matplotlib subplot share axis labels
  • Matplotlib subplot spacing between plots
  • Matplotlib subplot spacing automatic
  • Matplotlib subplots different sizes
  • Matplotlib subplot gridspec
  • Matplotlib subplot grid lines
  • Matplotlib subplot grid spacing
  • Matplotlib subplot grid color
  • Matplotlib subplot images
  • Matplotlib subplot image size
  • Matplotlib subplot imshow colorbar
  • Matplotlib subplot 3D

Matplotlib subplot

Matplotlib provides the feature to create a figure with multiple plots in a single call, with proper control over each plot in the figure, individually.

We can create a figure with multiple subplots using the matplotlib.pyplot.subplot() function in python. The syntax is as follows:

matplotlib.pyplot.subplot(nrows, ncols, idx [, label, projection, ...])

In the above syntax,

  • nrows specifies the number of rows in the grid, drawn on the figure for subplots.
  • ncols specifies the number of columns in the grid, drawn on the figure for subplots.
  • idx specifies the index position of the plot on the grid. The index starts from 1 at the upper-left corner and increases to the right.
  • idx can also be specified as a tuple of two integers specfying the first and last indices including the last index in the grid. For example, subplots(6, 2, (1, 4)) will fill the upper 1/3rd (i.e., 4/6th) part of the figure.
  • There are some other optional parameters like label, projection, sharex, sharey, polar, etc.
  • This command returns the axes of the subplots as axes.SubplotBase (base class) or another subclass of the Axes. The returned axes is the subplot base class if the projection specified is rectilinear projection (default projection) and the returned axes is a subplot subclass of the base class, if the projection specified is polar projection.

NOTE: The 3-digit integer can be passed in the matplotlib.pyplot.subplot() function, where the 3-digits represent the 3 parameters of the function. For example, matplotlib.pyplot.subplot(437) is the same as matplotlib.pyplot.subplot(4, 3, 7) in python, where a plot is added in a figure having 4 rows and 3 columns, and the plot is added to the 3rd-row’s 1st-column(at the 7th index).

Let’s do some examples to practice the concepts:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g')

# Plot 2
plt.subplot(2, 2, 2)
plt.plot(x, y2, '-.r')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, ':y')

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--c')

plt.show()
Matplotlib subplot
Matplotlib subplot

Read: Matplotlib plot bar chart

Matplotlib subplot figure size

We can adjust the size of the figure containing the subplots in the matplotlib by specifying a list of two values against the figsize parameter in the matplotlib.pyplot.figure() function, where the 1st value specifies the width of the figure and the 2nd value specifies the height of the figure.

Now, let’s practice the concept:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[9, 7])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)

plt.show()
Matplotlib subplot figure size
Matplotlib subplot figure size

We have adjusted the size of the figure, and so the layout of the subplots gets better.

Read: What is matplotlib inline

Matplotlib subplot title overall

We can give a title to the figure containing subplots in the matplotlib by specifying the title text in the matplotlib.pyplot.suptitle() function.

Let’s see, how it is done through an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)

plt.show()
Matplotlib subplot title overall
Matplotlib subplot title overall

Matplotlib subplot title for each plot

We can also give the title to each subplot in the figure in the matplotlib by specifying the title text in the matplotlib.pyplot.title() function with each subplot commands individually.

Let’s practice it through an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve')

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve')

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve')

plt.show()
Matplotlib subplot title for each plot
Matplotlib subplot title for each plot

Read: Python plot multiple lines using Matplotlib

Matplotlib subplot title font size

We can specify the font size of the title text (for both figure title and subplot title) in the matplotlib by adding a parameter fontsize with the necessary integer value of the size of the font in the matplotlib.pyplot.suptitle() or/and matplotlib.pyplot.title() function.

Let’s practice an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', fontsize=19)

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15)

plt.show()
Matplotlib subplot title font size
Matplotlib subplot title font size

We have adjusted the size of the fonts of the title text of the figure and the subplots.

Read: Matplotlib plot a line

Matplotlib subplot title bold

We can make the font of the title text to be bold (for both figure title and subplot title) in the matplotlib by adding a parameter fontweight with the necessary integer value (600+ for the bold font) or the string ‘bold’ in the matplotlib.pyplot.suptitle() or/and matplotlib.pyplot.title() function.

Example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15)

plt.show()
Matplotlib subplot title bold
Matplotlib subplot title bold

We have changed the font-weight to make the title text bold for the figure.

Read: modulenotfounderror: no module named ‘matplotlib’

Matplotlib subplot title position

We can specify the position of the title text of the figure by adding two more parameters x and y in the matplotlib.pyplot.suptitle() function. The values to the x and y parameters represent the x and y coordinates respectively in the figure coordinates.

Let’s see how can we implement the concept:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', x=0.5, y=0, fontsize=17, fontweight='700')

## Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', loc='left', fontsize=15)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', loc='right', fontsize=15)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', loc='left', fontsize=15)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', loc='right', fontsize=15)

plt.show()
Matplotlib subplot title position
Matplotlib subplot title position

We have set the different positions of the various title texts in the figure.

Read: How to install matplotlib python

Matplotlib subplot title padding

We can adjust the padding of the title text of the figure by adding a parameter y in the matplotlib.pyplot.suptitle() function and can add either y or the pad parameter in the matplotlib.pyplot.title() function. The value to the y parameters represents the y-coordinate in the figure coordinates and the value of the pad represents the gap/padding of the title text from the plot/subplot. The value of y ranges from 0 to 1.

Let’s see an example to understand the concepts better:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', y=1.1, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, y=1.1)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, y=1.1)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15, pad=17)

plt.show()
Matplotlib subplot title padding
Matplotlib subplot title padding

We have adjusted the padding of the title text of the figure and subplots.

Matplotlib subplot legend

We can add the legend to each subplot in the matplotlib by adding the matplotlib.pyplot.legend() function for each subplot.

Let’s see the implementation through an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

#Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2, label='1st degree curve')
plt.title('Plot 1', fontsize=15)
plt.legend(loc='upper left')

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k', label='2nd degree curve')
plt.title('Plot 2', fontsize=15)
plt.legend(loc='upper left')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3, label='3rd degree curve')
plt.title('Plot 3', fontsize=15)
plt.legend(loc='upper left')

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3, label='4th degree curve')
plt.title('Plot 4', fontsize=15)
plt.legend(loc='upper left')

plt.show()
Matplotlib subplot legend
Matplotlib subplot legend

We can also add a legend that is shared with all the subplots in the figure in matplotlib. We have to plot the figure by defining the axes and the figure using matplotlib.pyplot.subplots() function, and defining a global legend for the figure using figure.legend() with the following parameters:

  • A list of all the plot (line2D) objects (Here, curves) that we want to add in the legend.
  • labels: A list of the labels, for each plot (curve) objects.
  • loc: location of the legend (optional)
  • title: title of the legend (optional)

Let’s practice through an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Defining figure and axes objects using matplotlib.pyplot.subplots()
fig, ax = plt.subplots(2, 2, figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

fig.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
c1 = ax[0,0].plot(x, y1, 'g', linewidth=2)
ax[0,0].set_title('Plot 1', fontsize=15)

# Plot 2
c2 = ax[0,1].scatter(x, y2, color='k')
ax[0,1].set_title('Plot 2', fontsize=15)

# Plot 3
c3 = ax[1,0].plot(x, y3, '-.y', linewidth=3)
ax[1,0].set_title('Plot 3', fontsize=15)

# Plot 4
c4 = ax[1,1].plot(x, y4, '--b', linewidth=3)
ax[1,1].set_title('Plot 4', fontsize=15)

label_list = ['1st degree curve', '2nd degree curve', '3rd degree curve', '4th degree curve']

fig.legend([c1, c2, c3, c4],
           labels=label_list,
           loc='upper left',
           borderaxespad=0.1)

plt.show()
Matplotlib subplot shared legend
Matplotlib subplot shared legend

We have created a common legend shared by all the subplots of the figure.

Matplotlib subplot share axis

We can create a figure with either one or both of the axis shared across the subplots in matplotlib. We have to specify the sharex and sharey parameters to True in the matplotlib.pyplot.subplots() function. The y-axis cannot be shared vertically and the x-axis cannot be shared horizontally for the subplots. Sharing axes results in the common xticks and yticks for the subplots.

Let’s take a look at the implementation of the concept:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x + 3
y2 = x + 9
y3 = x + 13
y4 = x + 17

# Defining figure and axes objects using matplotlib.pyplot.subplots()
fig, ax = plt.subplots(2, 2, figsize=[11, 9])

fig.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
ax[0,0].plot(x, y1, 'g', linewidth=2)
ax[0,0].set_title('Plot 1: 1st degree curve', fontsize=15)

# Plot 2
ax[0,1].scatter(x, y2, color='k')
ax[0,1].set_title('Plot 2: 2nd degree curve', fontsize=15)

# Plot 3
ax[1,0].plot(x, y3, '-.y', linewidth=3)
ax[1,0].set_title('Plot 3: 3rd degree curve', fontsize=15)

# Plot 4
ax[1,1].plot(x, y4, '--b', linewidth=3)
ax[1,1].set_title('Plot 4: 4th degree curve', fontsize=15)

plt.show()

# ---------------------------------------------------------------------

# Defining figure and axes objects using matplotlib.pyplot.subplots()
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, figsize=[11, 9])

fig.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
ax[0,0].plot(x, y1, 'g', linewidth=2)
ax[0,0].set_title('Plot 1: 1st degree curve', fontsize=15)

# Plot 2
ax[0,1].scatter(x, y2, color='k')
ax[0,1].set_title('Plot 2: 2nd degree curve', fontsize=15)

# Plot 3
ax[1,0].plot(x, y3, '-.y', linewidth=3)
ax[1,0].set_title('Plot 3: 3rd degree curve', fontsize=15)

# Plot 4
ax[1,1].plot(x, y4, '--b', linewidth=3)
ax[1,1].set_title('Plot 4: 4th degree curve', fontsize=15)

plt.show()
Matplotlib subplot share axis
Matplotlib subplot share axis

We have created two figures, one with a not-shared axis and the other with a shared x-axis and y-axis.

Matplotlib subplot share axis labels

There is no direct method to add the common axis labels to the figure in matplotlib, but we can do it by a trick.

  • First, we will create a figure with the subplots.
  • Then, we will add an axes of the size of the figure that will encapsulate all the subplots using the figure.add_subplot() function.
  • And then we will disable the ticks and tick labels of this new plot, and showing the axis labels only. We can do so by specifying the parameters labelcolor=”none”, bottom=False, and left=False in the matplotlib.pyplot.tick_param() function.
  • Now, we can add the x-axis and y-axis labels to this bigger plot.

Let’s implement the above trick to better understand it:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x + 3
y2 = x + 9
y3 = x + 13
y4 = x + 17

# Defining figure and axes objects using matplotlib.pyplot.subplots()
fig, ax = plt.subplots(2, 2, figsize=[11, 9])

fig.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
ax[0,0].plot(x, y1, 'g', linewidth=2)
ax[0,0].set_title('Plot 1: 1st degree curve', fontsize=15)

# Plot 2
ax[0,1].scatter(x, y2, color='k')
ax[0,1].set_title('Plot 2: 2nd degree curve', fontsize=15)

# Plot 3
ax[1,0].plot(x, y3, '-.y', linewidth=3)
ax[1,0].set_title('Plot 3: 3rd degree curve', fontsize=15)

# Plot 4
ax[1,1].plot(x, y4, '--b', linewidth=3)
ax[1,1].set_title('Plot 4: 4th degree curve', fontsize=15)

# Adding a plot in the figure which will encapsulate all the subplots with axis showing only
fig.add_subplot(1, 1, 1, frame_on=False)

# Hiding the axis ticks and tick labels of the bigger plot
plt.tick_params(labelcolor="none", bottom=False, left=False)

# Adding the x-axis and y-axis labels for the bigger plot
plt.xlabel('Common X-Axis', fontsize=15, fontweight='bold')
plt.ylabel('Common Y-Axis', fontsize=15, fontweight='bold')

plt.show()
Matplotlib subplot share axis labels
Matplotlib subplot share axis labels

We can also create a figure with shared axis labels on the shared axes to the subplots in matplotlib.

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x + 3
y2 = x + 9
y3 = x + 13
y4 = x + 17

# Defining figure and axes objects using matplotlib.pyplot.subplots(),
# specifying the sharing of x-axis and y-axis to the subplots
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, figsize=[11, 9])

fig.suptitle('Different degree curves', fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
ax[0,0].plot(x, y1, 'g', linewidth=2)
ax[0,0].set_title('Plot 1: 1st degree curve', fontsize=15)

# Plot 2
ax[0,1].scatter(x, y2, color='k')
ax[0,1].set_title('Plot 2: 2nd degree curve', fontsize=15)

# Plot 3
ax[1,0].plot(x, y3, '-.y', linewidth=3)
ax[1,0].set_title('Plot 3: 3rd degree curve', fontsize=15)

# Plot 4
ax[1,1].plot(x, y4, '--b', linewidth=3)
ax[1,1].set_title('Plot 4: 4th degree curve', fontsize=15)

# Adding a plot in the figure which will encapsulate all the subplots with axis showing only
fig.add_subplot(1, 1, 1, frame_on=False)

# Hiding the axis ticks and tick labels of the bigger plot
plt.tick_params(labelcolor="none", bottom=False, left=False)

# Adding the x-axis and y-axis labels for the bigger plot
plt.xlabel('X-Axis', fontsize=15, fontweight='bold')
plt.ylabel('Y-Axis', fontsize=15, fontweight='bold')

plt.show()
Matplotlib subplot axis labels to shared axis
Matplotlib subplot axis labels to shared axis

We have created a figure containing four subplots with shared axis and axis labels.

Matplotlib subplot spacing between plots

We can adjust the spacing between the subplots of a figure in matplotlib by adding a function matplotlib.pyplot.subplots_adjust() with relevant parameter values. The following parameters can be specified according to the needs:

  • top: It specifies the top (upper part) of the subplots of the figure.
  • bottom: It specifies the bottom (lower part) of the subplots of the figure.
  • left: It specifies the left side of the subplots of the figure.
  • right: It specifies the right side of the subplots of the figure.
  • wspace: It specifies the width to be reserved for the blank space between the subplots.
  • hspace: It specifies the height to be reserved for the blank space between the subplots.

Let’s try out the implementation of the above method:

# Change the figure size
plt.figure(figsize=[11, 9])

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', y=1.13, fontsize=19, fontweight='bold')

plt.subplots_adjust(left=0.13, right=0.93, top=1.0, bottom= 0.27, wspace= 0.3, hspace=0.3)

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, y=1.1)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, y=1.1)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

plt.show()
Matplotlib subplot spacing between plots
Matplotlib subplot spacing between plots

We have added spaces between subplots of a figure.

Matplotlib subplot spacing automatic

There is a way in matplotlib to adjust the spacing of the subplots of a figure automatically according to the figure. We just need to add a function matplotlib.pyplot.tight_layout().

We can also give extra padding by specifying the parameters pad, w_pad, h_pad in the matplotlib.pyplot.tight_layout() function. These parameters provide control over extra padding around the figure’s border and between subplots. The values for their parameters are specified in terms of the fraction of the font size.

Let’s implement the function through an example:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

plt.suptitle('Different degree curves', y=1.13, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, y=1.1)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, y=1.1)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15, pad=17)

plt.show()

# ---------------------------------------------------------------------

# Plotting the subplots with auto adjust layout using matplotlib.pyplot.tight_layout()

plt.suptitle('Different degree curves', y=1.13, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, y=1.1)

# Plot 2
plt.subplot(2, 2, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, y=1.1)

# Plot 3
plt.subplot(2, 2, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)

# Plot 4
plt.subplot(2, 2, 4)
plt.plot(x, y4, '--b', linewidth=3)
plt.title('Plot 4: 4th Degree curve', fontsize=15, pad=17)

plt.tight_layout()
plt.show()
Matplotlib subplot spacing automatic
Matplotlib subplot spacing automatic

We have created two figures, one with not including tight_layout() function and the other with including it.

Matplotlib subplots different sizes

We can create a figure with different sized subplots in matplotlib with compatible grid specifications. We can do this by dividing the figure into the subplots and subplots of these subplots and so on. Then, specify the required subplots only.

Let’s take a look at the example for better understanding:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3

# Change the figure size
plt.figure(figsize=[11, 9])

plt.suptitle('Different degree curves', y=1.05, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 2
plt.subplot(2, 2, 3)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 3
plt.subplot(1, 2, 2)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

plt.tight_layout()
plt.show()
Matplotlib subplots different sizes
Matplotlib subplots different sizes

We have created 3 subplots of different sizes in a figure.

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

# Change the figure size
plt.figure(figsize=[11, 9])

plt.suptitle('Different degree curves', y=1.05, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(3, 1, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 2
plt.subplot(3, 2, 3)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 3
plt.subplot(3, 2, 4)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Plot 4
plt.subplot(3, 1, 3)
plt.plot(x, y4, ':r', linewidth=2)
plt.title('Plot 4: 4th Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

plt.tight_layout()
plt.show()
Matplotlib subplots different sized grids
Matplotlib subplots different sized grids

Matplotlib subplot gridspec

We can customize the figure layouts using the gridspec function in matplotlib. We can specify the geometry of the grid of the figure on which the subplots are to be placed by using gridspec function.

We have to specify the number of rows and number of columns of the grid of the figure. We can also adjust the subplot’s layout parameters like left, right, bottom, etc.

The syntax to use the gridspec function is as follows:

from matplotlib import pyplot as plt
from matplotlib import gridspec

fig = plt.figure()

grid_obj = gridspec.GridSpec(nrows, ncols[, figure, left, bottom, right, top, wspace, hspace, ...])

ax1 = fig.add_subplot(grid_obj[0, 0])
ax2 = fig.add_subplot(grid_obj[0, 1])
...
...
...
axN = fig.add_subplot(grid_obj[nrows-1, ncols-1])

In the above syntax,

  • The gridspec.GridSpec() is the function used to create a grid of nrows rows and ncols columns in the figure. The following parameters provide control over different layout parameters:
    • nrows specifies the number of rows in the grid.
    • ncols specifies the number of rcolumns in the grid.
    • figure specifies the figure on which the grids are to be placed. It is optional and by default it is None.
    • left, bottom, right, and top are the optional parameters that defines the extent of the subplots as the fraction of the figure width and height. NOTE- left cannot be greater than right and bottom cannot be greater than top.
    • wspace and hspace are the optional parameters that defines the amount of width and height reserved for the space between the subplots expressed as the fraction of the average axis width and height respectively.
  • grid_obj is the grid object returned by the gridspec.GridSpec() function.
  • After creating the grid_obj grid object, adding the subplots to with grid_obj specified grid for the subplots.

Let’s do some hands-on practice examples to create grids using the gridspec() function:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x + 3
y2 = x ** 2
y3 = x ** 3
y4 = x ** 4

fig = plt.figure(constrained_layout=True)
spec = gridspec.GridSpec(ncols=2, nrows=2, figure=fig)

# Plot 1
ax1 = fig.add_subplot(spec[0, 0])
ax1.plot(x, y1, 'g', linewidth=2)
ax1.set_title('Plot 1: 1st degree curve', fontsize=15)

# Plot 2
ax2 = fig.add_subplot(spec[0, 1])
ax2.scatter(x, y2, color='k')
ax2.set_title('Plot 2: 2nd degree curve', fontsize=15)

# Plot 3
ax3 = fig.add_subplot(spec[1, 0])
ax3.plot(x, y3, '-.y', linewidth=3)
ax3.set_title('Plot 3: 3rd degree curve', fontsize=15)

# Plot 4
ax4 = fig.add_subplot(spec[1, 1])
ax4.plot(x, y4, '--b', linewidth=3)
ax4.set_title('Plot 4: 4th degree curve', fontsize=15)

plt.show()
Matplotlib subplot gridspec
Matplotlib subplot gridspec

Let’s do an example to create different sized subplots using gridspec() function:

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y = []
y.append(x + 3)
y.append(x ** 2)
y.append(x ** 3)
y.append(x ** 4)

l_style = ['-', ':', '-.', '--']
l_color = ['g', 'k', 'y', 'b']
k = 0

fig2 = plt.figure(figsize=[7, 5], constrained_layout=True)
widths = [1.5, 3]
heights = [2, 3]
spec2 = fig2.add_gridspec(ncols=2, nrows=2, width_ratios=widths,
                          height_ratios=heights)
for row in range(2):
    for col in range(2):
        ax = fig2.add_subplot(spec2[row, col])
        ax.plot(x, y[k], color=l_color[k], linestyle=l_style[k],
                linewidth=3)
        ax.set_title('Plot'+str(k+1)+' : '+str(k+1)+' degree curve',
                     fontsize=15)
        k += 1

plt.show()
Matplotlib subplot gridspec different size subplots
Matplotlib subplot gridspec different size subplots

Matplotlib subplot grid lines

We can add grid lines in the subplots of the figure in matplotlib by adding the matplotlib.pyplot.grid() funcion for each subplot.

Let’s do some practice examples:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

 Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3

# Change the figure size
plt.figure(figsize=[11, 5])

plt.suptitle('Different degree curves', y=1.13, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(1, 3, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

# Plot 2
plt.subplot(1, 3, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

# Plot 3
plt.subplot(1, 3, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

plt.tight_layout()
plt.show()

# ---------------------------------------------------------------------

# Change the figure size
plt.figure(figsize=[11, 11])

plt.suptitle('Different degree curves', y=1.13, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(3, 1, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

# Plot 2
plt.subplot(3, 1, 2)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

# Plot 3
plt.subplot(3, 1, 3)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=17)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()

plt.tight_layout()
plt.show()
Matplotlib subplot grid lines
Matplotlib subplot grid lines

Matplotlib subplot grid spacing

We can adjust the gaps/spaces between the grid lines in the matplotlib by increasing the xticks and yticks values of the subplots in the figure. We can change the xticks and yticks range of a plot/subplot by using xlim() and ylim() respectively.

Let’s do some examples showing the way to adjust grid lines spacing:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np


# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3

# Changing the Matplotlib plot grid spacing by changing the spacing of
# the ticks

# Change the figure size
plt.figure(figsize=[11, 9])

plt.suptitle('Different degree curves', y=1.05, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.xlim(0, 12)
plt.ylim(0, 12)
plt.grid()

# Plot 2
plt.subplot(2, 2, 3)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.xlim(0, 15)
plt.ylim(0, 150)
plt.grid(alpha=0.8)

# Plot 3
plt.subplot(1, 2, 2)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.xlim(0, 15)
plt.ylim(0, 1500)
plt.grid(alpha=0.6)

plt.tight_layout()
plt.show()
Matplotlib subplot grid spacing
Matplotlib subplot grid spacing

Matplotlib subplot grid color

We can change and specify the color of the gridlines in the subplots of a figure in matplotlib by adding the parameter color with the value as a color name, color code, or a color hex code in the matplotlib.pyplot.grid() function.

We can also add the parameters like lifestyle, linewidth, etc as per needs in the matplotlib.pyplot.grid() function.

Let’s do an example for practice:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Preparing the data to subplots
x = np.linspace(0, 10, 10)
y1 = x
y2 = x ** 2
y3 = x ** 3

# Change the figure size
plt.figure(figsize=[11, 9])

plt.suptitle('Different degree curves', y=1.05, fontsize=19, fontweight='bold')

# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, 'g', linewidth=2)
plt.title('Plot 1: 1st Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis', fontsize=13)
plt.ylabel('Y-Axis', fontsize=13)
plt.xlim(0, 12)
plt.ylim(0, 12)
plt.grid(color='red', linestyle='-.', linewidth=1)

# Plot 2
plt.subplot(2, 2, 3)
plt.scatter(x, y2, color='k')
plt.title('Plot 2: 2nd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis', fontsize=13)
plt.ylabel('Y-Axis', fontsize=13)
plt.xlim(0, 15)
plt.ylim(0, 150)
plt.grid(alpha=0.8, color='blue', linestyle=':', linewidth=1.2)

# Plot 3
plt.subplot(1, 2, 2)
plt.plot(x, y3, '-.y', linewidth=3)
plt.title('Plot 3: 3rd Degree curve', fontsize=15, pad=12)
plt.xlabel('X-Axis', fontsize=13)
plt.ylabel('Y-Axis', fontsize=13)
plt.xlim(0, 15)
plt.ylim(0, 1500)
plt.grid(alpha=0.6, color='green', linestyle='--', linewidth=1.4)

plt.tight_layout()
plt.show()
Matplotlib subplot grid color
Matplotlib subplot grid color

Matplotlib subplot images

We can import and plot the images from the local system as in subplots of a figure in matplotlib. We can use the matplotlib.image submodule to import, read and show the image format in the matplotlib figure.

We can use the matplotlib.image.imread() function to import and read the image format file. An argument specifying the string containing the image file’s path in the system, followed by its name has to be specified. It will return an image object.

We can use the axes.imshow() function to plot the image object on the axes specified.

Let’s do some hands-on practice examples to better understand the concept:

# Import necessary libraries
import matplotlib.pyplot as plt

import matplotlib.image as img
import random
import os

cwd = os.getcwd()
source_path = cwd + '\\image_data\\'

fig, ax = plt.subplots(2,2)
plt.suptitle('Random Images', y=1.05, fontsize=19, fontweight='bold')

for i in range(2):
    for j in range(2):
        image_file = random.choice(os.listdir(source_path))
        image_path = os.path.join(source_path, image_file)
        image = img.imread(image_path)
        
        ax[i,j].set_title(image_file, fontsize=15, pad=12)
        ax[i,j].imshow(image)
        ax[i,j].grid()

plt.tight_layout()
plt.show()

# ------------------------------------------------------------------

plt.figure()
plt.suptitle('Random Images', y=1.05, fontsize=19, fontweight='bold')

for i in range(4):
    image_file = random.choice(os.listdir(source_path))
    image_path = os.path.join(source_path, image_file)
    image = img.imread(image_path)
    
    plt.subplot(2, 2, i+1)
    plt.title(image_file, fontsize=15, pad=12)
    plt.imshow(image)

plt.tight_layout()
plt.show()
Matplotlib subplot images
Matplotlib subplot images

Read: Matplotlib subplots_adjust

Matplotlib subplot image size

We can change the size of the image in the subplots of a figure in matplotlib by changing the size of the figure.

We can change the size of the figure using matplotlib.pyplot.figure() function with the argument figsize specifying the size of the figure in terms of a list of two values representing the width and the height of the figure.

Example:

# Import necessary libraries
import matplotlib.pyplot as plt

import matplotlib.image as img
import random
import os

cwd = os.getcwd()
source_path = cwd + '\\image_data\\'

plt.figure(figsize=[7, 7])
plt.suptitle('Random Images', y=1.05, fontsize=19, fontweight='bold')

for i in range(4):
    image_file = random.choice(os.listdir(source_path))
    image_path = os.path.join(source_path, image_file)
    image = img.imread(image_path)
    
    plt.subplot(2, 2, i+1)
    plt.title(image_file, fontsize=15, pad=12)
    plt.imshow(image)
    plt.grid()

plt.tight_layout()
plt.show()
Matplotlib subplot image size
Matplotlib subplot image size

We have adjusted the size of the figure to adjust the size of the subplots with it.

Read: Matplotlib best fit line

Matplotlib subplot imshow colorbar

We can create a common colorbar for all the subplot images in the figure in matplotlib.

We can add separate axes for the colorbar by using matplotlib.figure.Figure.add_axes() function with a parameter representing the dimensions as a list of 4 values [left, bottom, width, height] and plot the colorbar on that axes.

We can use the matplotlib.figure.Figure.colorbar() function to create a colorbar and specify the parameters mappable which represents the object of the plot whose colors is to be mapped in the colorbar, and cax that represents the axes on which the colorbar has to be drawn.

Let’s create colorful image plots and add a common colorbar for all the subplots in the figure:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 2, figsize=[7, 7])

for x in ax.flat:
    image = x.imshow(np.random.random((15,15)), vmin=0, vmax=1)

fig.subplots_adjust(right=0.8)
color_bar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(image, cax=color_bar_ax)

plt.show()
Matplotlib subplot imshow colorbar
Matplotlib subplot imshow colorbar

Read: What is Matplotlib

Matplotlib subplot 3D

We can create a figure with 3D subplots in matplotlib. We can use the mpl_toolkits.mplot3d.axes3d sub-module to create 3D axes and plot 3D shapes in matplotlib.

We can add the axes by using the figure.add_subplot() function with an additional parameter projection valued as ‘3d’. And then create a 3D plot and add it to the previously defined axes with 3d projection.

We can do the above method separately to create multiple subplots by adding more axes with 3D shapes to the figure.

Let’s create some 3D plots (here, surface plot and wireframe) and add them into a figure:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

from matplotlib import cm                # for using the colormap
from mpl_toolkits.mplot3d.axes3d import get_test_data


fig = plt.figure(figsize=[9, 4])

plt.suptitle('3D plots', y=1.05, fontsize=19, fontweight='bold')

# Subplot 1
# set up the axes for the first plot
ax = fig.add_subplot(1, 2, 1, projection='3d')

# Plotting a 3D surface in first subplot
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)

R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

surface_pl = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                             cmap=cm.coolwarm, linewidth=0)
ax.set_zlim(-1.01, 1.01)

fig.colorbar(surface_plt, shrink=0.5, aspect=10)
ax.set_title('A 3D Surface')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')


# Subplot 2
# set up the axes for the second plot
ax = fig.add_subplot(1, 2, 2, projection='3d')

# Plotting a 3D wireframe in second subplot
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

ax.set_title('A 3D Wireframe')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')

plt.tight_layout()
plt.show()
Matplotlib subplot 3D
Matplotlib subplot 3D

We have created a surface plot with colorbar and a wireframe plot and added them into a figure.

In this Python tutorial, we have discussed the matplotlib subplot in python, which lets us work with multiple plots in a figure and we have also covered the following topics:

  • Matplotlib subplot figure size
  • Matplotlib subplot title overall
  • Matplotlib subplot title for each plot
  • Matplotlib subplot title font size
  • Matplotlib subplot title bold
  • Matplotlib subplot title position
  • Matplotlib subplot title padding
  • Matplotlib subplot legend
  • Matplotlib subplot share axis
  • Matplotlib subplot share axis labels
  • Matplotlib subplot spacing between plots
  • Matplotlib subplot spacing automatic
  • Matplotlib subplots different sizes
  • Matplotlib subplot gridspec
  • Matplotlib subplot grid lines
  • Matplotlib subplot grid spacing
  • Matplotlib subplot grid color
  • Matplotlib subplot images
  • Matplotlib subplot image size
  • Matplotlib subplot imshow colorbar
  • Matplotlib subplot 3D