Skip to content Skip to sidebar Skip to footer

How To Make More Than 10 Subplots In A Figure?

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 t

Solution 1:

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 inrange(5):
    for j inrange(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.

Post a Comment for "How To Make More Than 10 Subplots In A Figure?"