18

I am trying to make a 5x4 grid of subplots, and from looking at examples it seems to me that the best way is:

import matplotlib.pyplot as plt
plt.figure()
plt.subplot(221)

where the first two numbers in the subplot (22) indicate that it is a 2x2 grid and the third number indicates which one of the 4 you are making. However, when I tried this I had to go up to:

plt.subplot(5420)

and I got the error:

ValueError: Integer subplot specification must be a three digit number.  Not 4

So does that mean you cannot make more that 10 subplots, or is there a way around it, or am I misunderstanding how it works?

Thank you in advance.

Sam V
  • 323
  • 1
  • 2
  • 6
  • 16
    Use commas: `plt.subplot(5,4,20)`. You can find this behavior referenced in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot). – wflynny May 24 '16 at 21:59
  • Also relevant (although low quality question): https://stackoverflow.com/questions/35510155/matplotlib-subplot – wflynny May 24 '16 at 22:04

1 Answers1

37

You are probably looking for GridSpec. You can state the size of your grid (5,4) and the position for each plot (row = 0, column = 2, i.e. - 0,2). Check the following example:

import matplotlib.pyplot as plt

plt.figure(0)
ax1 = plt.subplot2grid((5,4), (0,0))
ax2 = plt.subplot2grid((5,4), (1,1))
ax3 = plt.subplot2grid((5,4), (2, 2))
ax4 = plt.subplot2grid((5,4), (3, 3))
ax5 = plt.subplot2grid((5,4), (4, 0))
plt.show()

, which results in this:

gridspec matplotlib example

Should you build nested loops to make your full grid:

import matplotlib.pyplot as plt

plt.figure(0)
for i in range(5):
    for j in range(4):
        plt.subplot2grid((5,4), (i,j))
plt.show()

, you'll obtain this:

full 5x4 grid in gridspec matplotlib

The plots works the same as in any subplot (call it directly from the axes you've created):

import matplotlib.pyplot as plt
import numpy as np

plt.figure(0)
plots = []
for i in range(5):
    for j in range(4):
        ax = plt.subplot2grid((5,4), (i,j))
        ax.scatter(range(20),range(20)+np.random.randint(-5,5,20))
plt.show()

, resulting in this:

multiple scatterplots in gridspec

Notice that you can provide different sizes to plots (stating number of columns and rows for each plot):

import matplotlib.pyplot as plt

plt.figure(0)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))
plt.show()

, therefore:

different sizes for each plot in gridspec

In the link I gave in the beginning you will also find examples to remove labels among other stuff.

armatita
  • 12,825
  • 8
  • 48
  • 49