Skip to content

Plotting using Matplotlib

Single Plot

A single plot using the object-oriented interface
Single Plot
# mkdocs: render

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 10)
y1 = 5 * x
y2 = x ** 2
y3 = np.exp(x / 3)

fig, ax = plt.subplots()
ax.plot(x, y2, label=r'$y = x^2$')
ax.plot(x, y1, 'o-', color='red', label=r'$y = 5x$')
ax.plot(x, y3, 'o', color='tab:green', linestyle='--', label=r'$y = \exp(x/3)$')

ax.legend()
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_title('Single Plot')
ax.grid(True, linestyle='--')

# fig.savefig('out.png', dpi=120)

Multiple Plots: Grid

Multiple Plots Using a Uniform Grid
multiplot_grid.py
# mkdocs: render

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 10)
y = x ** 2

fig, ax = plt.subplots(
    nrows=2, 
    ncols=2, 
    sharex=True, 
    sharey=True, 
    layout='constrained',
)

ax[0, 0].plot(x, y)
ax[0, 1].plot(x, y, 'o-', color='red')
ax[1, 0].plot(x, y, 'o', color='tab:green', linestyle='--')
ax[1, 1].plot(x, y, '.', color='salmon', linestyle=':')

for i, axis in enumerate(ax.flat):
    axis.set_title(f'plot {i}')

fig.supxlabel('x-axis')
fig.supylabel('y-axis')
fig.suptitle('Multiple Plots')

# fig.savefig('out.png', dpi=120)

Multiple Plots: Mosaic

Multiple Plots Using a Mosiac Grid
multiplot_mosaic.py
# mkdocs: render

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.linspace(0, 6*np.pi, 100)

X, Y = np.meshgrid(x, y)
img = np.sin(X) + np.cos(Y)

fig, ax = plt.subplot_mosaic(
    mosaic='AAAB\nAAAB\nAAAB\nCCCD', # (1)!
    layout='constrained',
)

ax['A'].imshow(img, origin='lower', aspect='auto', extent=(0, 6*np.pi, 0, 6*np.pi), interpolation='gaussian')
ax['B'].plot(np.cos(x), y, '-', color='tab:red')
ax['C'].plot(x, np.sin(y), '-', color='tab:green')
ax['D'].axis(False)

ax['A'].sharex(ax['C'])
ax['A'].sharey(ax['B'])

# fig.savefig('out.png', dpi=120)
  1. The mosaic format is available in Matplotlib 3.1 and later