5

I am creating a figure in matplotlib's add_subplot() function.

When I run this

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(212) # why not 211

I get this output

enter image description here

My question is how this last argument works. Why it is 212 for ax4 instead of 211, since there is only one plot for 2nd row?

If I run with 211 instead of 212 as following:

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(211)

I get this output where Plot 4 places on Plot 2 on first row.

enter image description here

I would be appreciated if someone could explain how the indexing works. Spent quite time researching still did not get it.

malioboro
  • 3,097
  • 4
  • 35
  • 55
mmustafaicer
  • 434
  • 6
  • 15

1 Answers1

7

The index 212 used here is intentional. Here the first two indices means 2 rows and 1 column. When the third number is 1 (211), it means add the subplot in the first row. When the third number is 2 (212), it means add the subplot in the second row.

The reason that in the above example, 212 is used is because the first three lines ax1, ax2 and ax3 adds subplots to a 2 row and 3 column grid. If 211 is used for the fourth subplot (ax4), it will overlap with the first row of (231), (232) and (233). This can be seen in the second figure below where you see the ax4 overlapping the underlying 3 subplots. This is the reason ax4 is added in the second row of the 2 row 1 column figure using (212) instead of adding it to the first row of using (211)

If you use 212, you get the following output

fig = plt.figure()

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(212)

enter image description here

If you use 211, you get the following output. As you can see, the ax4 is covering the 3 subplots.

fig = plt.figure()

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(211)

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71