Creating multiple subplots using plt.subplots¶

pyplot.subplots creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created. For more advanced use cases you can use GridSpec for a more general subplot layout or Figure.add_subplot for adding subplots at arbitrary locations within the figure.

# sphinx_gallery_thumbnail_number = 11

import matplotlib.pyplot as plt
import numpy as np

# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

A figure with just one subplot¶

subplots() without arguments returns a Figure and a single Axes.

This is actually the simplest and recommended way of creating a single Figure and Axes.

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('A single plot') Out:

Text(0.5, 1.0, 'A single plot')

Stacking subplots in one direction¶

The first two optional arguments of pyplot.subplots define the number of rows and columns of the subplot grid.

When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.

fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs.plot(x, y)
axs.plot(x, -y) Out:

[<matplotlib.lines.Line2D object at 0x7f155f08beb0>]

If you are creating just a few Axes, it's handy to unpack them immediately to dedicated variables for each Axes. That way, we can use ax1 instead of the more verbose axs.

fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y) Out:

[<matplotlib.lines.Line2D object at 0x7f155eea5700>]

To obtain side-by-side subplots, pass parameters 1, 2 for one row and two columns.

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y) Out:

[<matplotlib.lines.Line2D object at 0x7f155f2f9ee0>]

Stacking subplots in two directions¶

When stacking in two directions, the returned axs is a 2D NumPy array.

If you have to set parameters for each subplot it's handy to iterate over all subplots in a 2D grid using for ax in axs.flat:.

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
ax.label_outer() You can use tuple-unpacking also in 2D to assign all subplots to dedicated variables:

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y**2, 'tab:orange')
ax3.plot(x, -y, 'tab:green')
ax4.plot(x, -y**2, 'tab:red')

for ax in fig.get_axes():
ax.label_outer() Sharing axes¶

By default, each Axes is scaled individually. Thus, if the ranges are different the tick values of the subplots do not align.

fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Axes values are scaled individually by default')
ax1.plot(x, y)
ax2.plot(x + 1, -y) Out:

[<matplotlib.lines.Line2D object at 0x7f152b3b62b0>]

You can use sharex or sharey to align the horizontal or vertical axis.

fig, (ax1, ax2) = plt.subplots(2, sharex=True)
fig.suptitle('Aligning x-axis using sharex')
ax1.plot(x, y)
ax2.plot(x + 1, -y) Out:

[<matplotlib.lines.Line2D object at 0x7f15483422b0>]

Setting sharex or sharey to True enables global sharing across the whole grid, i.e. also the y-axes of vertically stacked subplots have the same scale when using sharey=True.

fig, axs = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle('Sharing both axes')
axs.plot(x, y ** 2)
axs.plot(x, 0.3 * y, 'o')
axs.plot(x, y, '+') Out:

[<matplotlib.lines.Line2D object at 0x7f152b39c160>]

For subplots that are sharing axes one set of tick labels is enough. Tick labels of inner Axes are automatically removed by sharex and sharey. Still there remains an unused empty space between the subplots.

The parameter gridspec_kw of pyplot.subplots controls the grid properties (see also GridSpec). For example, we can reduce the height between vertical subplots using gridspec_kw={'hspace': 0}.

label_outer is a handy method to remove labels and ticks from subplots that are not at the edge of the grid.

fig, axs = plt.subplots(3, sharex=True, sharey=True, gridspec_kw={'hspace': 0})
fig.suptitle('Sharing both axes')
axs.plot(x, y ** 2)
axs.plot(x, 0.3 * y, 'o')
axs.plot(x, y, '+')

# Hide x labels and tick labels for all but bottom plot.
for ax in axs:
ax.label_outer() Apart from True and False, both sharex and sharey accept the values 'row' and 'col' to share the values only per row or column.

fig, axs = plt.subplots(2, 2, sharex='col', sharey='row',
gridspec_kw={'hspace': 0, 'wspace': 0})
(ax1, ax2), (ax3, ax4) = axs
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y**2, 'tab:orange')
ax3.plot(x + 1, -y, 'tab:green')
ax4.plot(x + 2, -y**2, 'tab:red')

for ax in axs.flat:
ax.label_outer() Polar axes¶

The parameter subplot_kw of pyplot.subplots controls the subplot properties (see also Figure.add_subplot). In particular, this can be used to create a grid of polar Axes.

fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
ax1.plot(x, y)
ax2.plot(x, y ** 2)

plt.show() Total running time of the script: ( 0 minutes 1.284 seconds)

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery
{"ft_lang_label":"__label__en","ft_lang_prob":0.56181973,"math_prob":0.9830701,"size":2463,"snap":"2022-05-2022-21","text_gpt3_token_len":695,"char_repetition_ratio":0.115087435,"word_repetition_ratio":0.0053475937,"special_character_ratio":0.2634998,"punctuation_ratio":0.17267552,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9979004,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],"im_url_duplicate_count":[null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-01-22T21:51:04Z\",\"WARC-Record-ID\":\"<urn:uuid:798aec79-3298-49bc-affb-4d67ee3a43a2>\",\"Content-Length\":\"68328\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:197d5189-2df5-4812-b842-35fa3cc969c7>\",\"WARC-Concurrent-To\":\"<urn:uuid:99152726-7a1b-40be-85f0-2334f8d51558>\",\"WARC-IP-Address\":\"172.67.74.104\",\"WARC-Target-URI\":\"https://matplotlib.org/3.2.0/gallery/subplots_axes_and_figures/subplots_demo.html\",\"WARC-Payload-Digest\":\"sha1:GCM366OJJSNVPDDLHQBXDHDQB4ADEEIR\",\"WARC-Block-Digest\":\"sha1:CPZTHTET3SEOSKBFEHKHRQYNIP75BDR5\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-05/CC-MAIN-2022-05_segments_1642320303884.44_warc_CC-MAIN-20220122194730-20220122224730-00054.warc.gz\"}"}