How can rows in a plot have different numbers of columns?



In the context of this exercise in Matplotlib, how can rows in a plot have different numbers of columns?


In order to understand how rows of a plot can have different numbers of columns, we first need to understand how the subplot essentially works.

When you apply subplot, you are not actually setting permanent dimensions for the layout of the plot grid.

Instead, think of it as though each time you use subplot, with some specified values, you are just creating a “virtual” or temporary grid layout placed on top of the entire plot area. After we place the subplot based on the layout of this grid, it is removed until we create a new subplot, with a new temporary grid.

For example, if we create a subplot as follows
ax1 = plt.subplot(2, 2, 1)
this will create a temporary 2x2 grid, and place the subplot at index 1 based on this 2x2 grid, which is the upper left.

And, if we wanted to add another subplot, say at the bottom right, we would do
ax2 = plt.subplot(2, 2, 4)
which again creates a temporary 2x2 grid, and places the subplot at index 4, which is the lower right area.

A way to visualize this would be

# [temp ] is used to signify temporary empty subplots
# when the virtual grid is applied.

# Adding ax1
[ ax1 ] [temp ]
[temp ] [temp ]

# Result plot
[ ax1 ]

# Adding ax2
[temp ] [temp ]
[temp ] [ ax2 ]

# Result plot
[ ax1 ] 
        [ ax2 ]

What essentially happens when we create a subplot is as follows:

It creates a temporary “virtual” grid on top of the entire plot area.

It places the subplot within the layout of that temporary grid at the specified index, based on that grid.

After the subplot is placed, that virtual or temporary grid disappears, and we have the subplots on the plot area, as we intended.

When we add another subplot, this process repeats.