Dynamically add/create subplots in matplotlib

Suppose you know total subplots and total columns you want to use:

import matplotlib.pyplot as plt

# Subplots are organized in a Rows x Cols Grid
# Tot and Cols are known

Tot = number_of_subplots
Cols = number_of_columns

# Compute Rows required

Rows = Tot // Cols 

#     EDIT for correct number of rows:
#     If one additional row is necessary -> add one:

if Tot % Cols != 0:
    Rows += 1

# Create a Position index

Position = range(1,Tot + 1)

First instance of Rows accounts only for rows completely filled by subplots, then is added one more Row if 1 or 2 or … Cols – 1 subplots still need location.

Then create figure and add subplots with a for loop.

# Create main figure

fig = plt.figure(1)
for k in range(Tot):

  # add every single subplot to the figure with a for loop

  ax = fig.add_subplot(Rows,Cols,Position[k])
  ax.plot(x,y)      # Or whatever you want in the subplot

plt.show()

Please note that you need the range Position to move the subplots into the right place.

Leave a Comment