Matlotplot - Subplots

I have got a question relating to the " Exploratory Data Visualization" chapter.

On page 4 of the “Multiple plots” section the following Dataquest code is given to produce a figure with 4 subplots:

"4 plots:"
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2) 
ax2 = fig.add_subplot(2,2,3) 
ax2 = fig.add_subplot(2,2,4)

This is the code that I expected:

"4 plots:"
ax1 = fig.add_subplot(4,2,1)
ax2 = fig.add_subplot(4,2,2) 
ax2 = fig.add_subplot(4,2,3) 
ax2 = fig.add_subplot(4,2,4)

Should it be a four instead of a two? Am I missing something?

Thanks for your help!

1 Like

Welcome eisslerpascal… Good question, this came up for me also during the guided project at the end of this section…look forward to getting clear on this

Hello @eisslerpascal @spader108,

The General syntax for adding subplots is :
axes_obj = fig.add_subplot(nrows, ncols, plot_number) .

The total number of subplots that can be added to the figure will be nrows multiplied by ncols.

Following this background,

The figure can only accommodate a total of 4 subplots.The code adds 4 subplots to the figure.

while,

This creates 8 subplots but adds only 4 subplots that was defined in the code to the figure. The 8 subplots are created such that it has 4 rows and 2 columns but only the first 2 rows are fully occupied by the subplots added.

Therefore, in the block of code can still accomodate 4 more subplots as in:

ax1 = fig.add_subplot(4,2,1)
ax2 = fig.add_subplot(4,2,2) 
ax3 = fig.add_subplot(4,2,3) 
ax4 = fig.add_subplot(4,2,4)
ax5 = fig.add_subplot(4,2,5)
ax6 = fig.add_subplot(4,2,6) 
ax7 = fig.add_subplot(4,2,7) 
ax8 = fig.add_subplot(4,2,8)

Another way to create 4 subplots is by defining 4 rows and 1 column as in:

ax1 = fig.add_subplot(4,1,1)
ax2 = fig.add_subplot(4,1,2) 
ax3 = fig.add_subplot(4,1,3) 
ax4 = fig.add_subplot(4,1,4)
plt.show()

I hope this helps.

1 Like

Thanks Doyin! Very helpful.

1 Like