how to create multiple sublplots using a for loop in python

You can create multiple subplots using a for loop in matplotlib as shown in the code below:

main.py
import matplotlib.pyplot as plt

# create a figure and axis objects
fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(12, 8))

# flatten axis objects for easy iteration using a for loop
axs_flat = axs.flatten()

# create subplots using a for loop
for i in range(6):
    x = [1, 2, 3, 4]
    y = [1, 4, 9, 16]
    axs_flat[i].plot(x, y)
    axs_flat[i].set_title(f'Plot {i+1}')

# add figure title
plt.suptitle('Multiple Subplots using For Loop', fontsize=16)

# show the plot
plt.show()
488 chars
21 lines

In this code, we first create a figure object and axis objects using plt.subplots(). We specify the number of rows and columns of subplots we want to create.

Next, we flatten the axis objects using the flatten() method, so that we can easily iterate over them using a for loop.

We then create multiple subplots using a for loop, where each subplot plots some data and has a title.

Finally, we add a title to the entire figure using plt.suptitle() and display the plot using plt.show().

related categories

gistlibby LogSnag