matplotlib side by side plots vertically and horizontally – Code Example

Matplotlib provides pyplot.subplots function which accepts number of rows and columns as arguments. These arguments are used to create plots side by side vertically and horizontally.

Code Example

The format of subplots function is –

matplotlib.pyplot.subplots(nrows=1, ncols=1)

If you want to plot side by side horizontally then increase column count –

matplotlib.pyplot.subplots(1, 2)

If you want to plot side by side vertically then increase rows count –

matplotlib.pyplot.subplots(2)

You can have multiple columns and rows in single plot too. Check out this complete example –

import matplotlib.pyplot as plt
import numpy as np

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()
plt.subplots side by side horizontal and vertical

Source: subplots_demo