I could use a harmless smoke after the last 2 days…
Today's topic is about subplots, smaller plots within a big plot, because we sometimes want to compare different data in the same figure.
In the image below are key components of a data figure:
Figure: refers to a large structure that contains all drawing results, axis names, titles, etc.
Axes: refers to each drawing block. Each block contains the drawing results of the graph.
Axis: refers to the coordinate axis of each plot, which determines how the plot is reasonably interpreted.
Compared to regular plots, subplots are their smaller cousins that can be displayed together at once. Their usefulness comes from the ability to have many of them displayed at once. More on how they are displayed together will be available in a later section.
Note that if you want to customize the drawn subplot (e.g., name an axis), the logic is to "customize for the subplot" rather than "customize for the result."
Just as there are grids in CSS, Python subplot figures can too be organized in the fashion of grids. Placing subplots into the same grid can be useful for comparing different data fields in the same figure, as well as saving space.
However, it is not recommended to place too many subplots in the same figure, as it might make the figure hard to read. We will address with mitigating this issue in a later section.
In practice, adding subplots to a figure is more convenient than adding subplots to a plot. The reasons are that the former is more flexible and can be used to create more complex plots, while the latter is more suitable for simple plots. Complex plots upon complex plots can be hard to manage.
Remember seeing the grid from above with subplot y-axes values overlapping with each other? For viewing purposes, you would want to widen the gap between them. You can straightforwardly do so by entering the plt.tight_layout() function right before plt.show().
If you additionally want your plots to display more categories in numerical x-axes, adding "constrained_layout = True" in plt.subplots() will also do the following, as well as auto-adjust the grid object's gaps to readable metrics.
If, for whatever reason, you want to display your subplots in a non-rectangular grid, you can use plt.GridSpec() to create a grid of subplots with different sizes.
Do note that GridSpec is also not very compatible to resize with .tight_layout() or .constrained_layout(), so you will have to adjust the size of the subplots manually via wspace and hspace.