Sometimes, when we’re putting multiple subplots together, some elements can overlap and make the figure unreadable:
We can customize the spacing between our subplots to make sure that the figure we create is visible and easy to understand. To do this, we use the plt.subplots_adjust()
command. .subplots_adjust()
has some keyword arguments that can move your plots within the figure:
left
— the left-side margin, with a default of 0.125. You can increase this number to make room for a y-axis labelright
— the right-side margin, with a default of 0.9. You can increase this to make more room for the figure, or decrease it to make room for a legendbottom
— the bottom margin, with a default of 0.1. You can increase this to make room for tick mark labels or an x-axis labeltop
— the top margin, with a default of 0.9wspace
— the horizontal space between adjacent subplots, with a default of 0.2hspace
— the vertical space between adjacent subplots, with a default of 0.2
For example, if we were adding space to the bottom of a graph by changing the bottom margin to 0.2 (instead of the default of 0.1), we would use the command:
plt.subplots_adjust(bottom=0.2)
We can also use multiple keyword arguments, if we need to adjust multiple margins. For instance, we could adjust both the top
and the hspace
:
plt.subplots_adjust(top=0.95, hspace=0.25)
Let’s use wspace
to fix the figure above:
# Left Plot plt.subplot(1, 2, 1) plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4]) # Right Plot plt.subplot(1, 2, 2) plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4]) # Subplot Adjust plt.subplots_adjust(wspace=0.35) plt.show()
This would give us figure with a better layout:
Instructions
We are going to create a figure that has two rows of subplots. It should have:
- one subplot in the top row
- two subplots in the bottom row
Start by using the subplot
method to instantiate the subplot in the top row (the box with the star in it).
Plot straight_line
vs x
in this subplot you’ve selected.
Now, use the plt.subplot()
command to select the box in the first column of the second row (the one with a square in it). Plot parabola
vs x
in this box.
Now, use the plt.subplot()
command to select the box in the second column of the second row (the one with a triangle in it). Plot cubic
vs x
in this box.
Increase the spacing between horizontal subplots to 0.35
and the bottom margin to 0.2
.