-
Basics Review 1
-
Lecture1.1
-
-
Subplots 2
-
Lecture2.1
-
Lecture2.2
-
-
3D Plots 2
-
Lecture3.1
-
Lecture3.2
-
-
Animation 1
-
Lecture4.1
-
Subplots Part 1
Subplots Part 1¶
Subplots are a great tool for combining multiple graphs into one image. They will save you a lot of time and effort in terms of formatting if you master them. To start with, calling plt.subplots() with the nrows argument creates n rows of subplots. We also can pass a figsize argument to make the plots larger. It will return a figure and the axes (an array).
import matplotlib.pyplot as plt
#Basic subplots can be called with a number of rows as nrows
#We can adjust the size to make it easier to see
fig, ax = plt.subplots(nrows=2, figsize=(12,8))
plt.show()
The way which we plot with subplots is to take the ax object, index which row we want to plot, then call plotting functions on it. In the code below, we make some data, and then we call ax[0] for the first plot and ax[1] for the second plot.
#Create data
X1 = list(range(0,101))
X2 = list(range(50,101))
Y1 = [10 * x for x in X1]
Y2 = [(x-50) ** 2 for x in X2]
#We can plot by indexing the axes
fig, ax = plt.subplots(nrows=2, figsize=(12,8))
ax[0].plot(X1, Y1)
ax[1].plot(X2, Y2)
plt.show()
In some cases, we want these plots to be aligned for the x-axis. You can see that right now they are not. The argument sharex set to True achieves this.
#It is possible to share the x-axis with sharex=True
fig, ax = plt.subplots(nrows=2, figsize=(12,8), sharex=True)
ax[0].plot(X1, Y1)
ax[1].plot(X2, Y2)
plt.show()
The argument of sharey achieves the same thing for the y-axis.
#It is possible to share the y-axis with sharey=True
fig, ax = plt.subplots(nrows=2, figsize=(12,8), sharex=True, sharey=True)
ax[0].plot(X1, Y1)
ax[1].plot(X2, Y2)
plt.show()
To set labels, we want to actually call the different ax objects (for example ax[0]) and use the functions set_xlabel and set_ylabel.
#It is also possible to set xlabels and ylabels
fig, ax = plt.subplots(nrows=2, figsize=(12,8), sharex=True, sharey=True)
ax[0].plot(X1, Y1)
ax[0].set_xlabel("Series 1 X")
ax[0].set_ylabel("Series 1 Y")
ax[1].plot(X2, Y2)
ax[1].set_xlabel("Series 2 X")
ax[1].set_ylabel("Series 2 Y")
plt.show()
Titles work in the same manner using set_title.
#It is also possible to set a title for each
fig, ax = plt.subplots(nrows=2, figsize=(12,8), sharex=True, sharey=True)
ax[0].plot(X1, Y1)
ax[0].set_xlabel("Series 1 X")
ax[0].set_ylabel("Series 1 Y")
ax[0].set_title("Series 1")
ax[1].plot(X2, Y2)
ax[1].set_xlabel("Series 2 X")
ax[1].set_ylabel("Series 2 Y")
ax[1].set_title("Series 2")
plt.show()