Subplots

Subplots#

As mentioned previously, a single Figure object can contain multiple Axes or plots. To create a Figure with two subplots, we pass number arguments to plt.subplots(). An example that compares dampened and undampened oscillation over time (in seconds).

%matplotlib inline
import matplotlib.pyplot as plt, numpy as np # import statement

x1 = np.linspace(0.0, 5.0) # create x axis for first subplot
x2 = np.linspace(0.0, 2.0) # create x axis for second subplot
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) # create y axis for first subplot
y2 = np.cos(2 * np.pi * x2) # create y axis for second subplot

fig, (ax1, ax2) = plt.subplots(2, 1) # create figure with two axes/subplots, stacked vertically on top of each other
fig.suptitle('A tale of 2 subplots') # set figure title

ax1.plot(x1, y1, 'o-') # first subplot
ax1.set_ylabel('Damped oscillation')

ax2.plot(x2, y2, '.-') # second subplot
ax2.set_xlabel('time (s)')
ax2.set_ylabel('Undamped')

plt.show() # show output

Additional Resources#

For more on subplots: