Subplot: how does it figure out the configuration?

### Adding the subplots
plt.figure(figsize=(12, 6))
ax1 = plt.subplot(2,3,1)
ax2 = plt.subplot(2,3,2)
ax3 = plt.subplot(2,3,3)
ax4 = plt.subplot(2,1,2)

In the solution notebook, cell 15, it uses the above lines to arrange the subplots.

How does it know that the first three plots belong to the first row of the last subplot (ax4 = plt.subplot(2,1,2))?!

Hi @sofiaaroman and welcome to the community!

It’s been a while since I’ve built such a plot but I remember struggling with this idea too. I’ll try to explain it as best I remember.

Before we can understand what’s happening with ax4, let’s look at the first three (ax1, ax2, and ax3) to make sure we know what’s going on there. Each of these objects are constructed with plt.subplot(2, 3, i) where i is the index number and the 2 refers to the number of rows while the 3 refers to the number of columns. This means that we created a 2x3 grid which could potentially display 6 plots in total; 3 plots on the first row (“one per column”) and potentially 3 more plots on the second row (“one per column”). So far so good?

Since indexing works from left to right and from top to bottom, indices 1, 2, and 3 are on the first row and indices 4, 5, and 6 would correspond to the second row. But we don’t want 6 plots, we only want 4! So what we really want to do is use the first row to create three plots (ax1, ax2, and ax3) and use the second row for one plot (ax4) that will use all three columns.

So when we use ax4 = plt.subplot(2,1,2) what we’re really saying is “hey, I want to access the second index of a 2x1 grid (2 rows, 1 column)” which is essentially the entire second row of our 2x3 grid. In other words, rather than have three separate plots on that second row (i.e. 3 columns), we want that entire second row to be one plot (i.e. one column, not three).

Since a 2x1 grid can hold two plots (one on the first row, one on the second row), plt.subplot(2,1,1) would refer to the first row (where we have ax1, ax2, and ax3) and plt.subplot(2,1,2) would refer to the entire second row of our 2x3 grid.

To see some examples of what I mean, search this tutorial for the heading “Matplotlib subplots different sizes” (just below half-way down the page). Focus on the calls to plt.subplot() and the parametres used to construct the plots with different sized subplots.