Looping through a function to plot several subplots, Python

扶醉桌前 提交于 2019-12-01 14:58:07

Use plt.subplots instead of plt.subplot (note the "s" at the end). fig, axs = plt.subplots(2, 3) will create a figure with 2x3 group of subplots, where fig is the figure, and axs is a 2x3 numpy array where each element is the axis object corresponding to the axis in the same position in the figure (so axs[1, 2] is the bottom-right axis).

You can then either use a pair of loops to loop over each row then each axis in that row:

fig, axs = plt.subplots(2, 3)
for i, row in enumerate(axs):
   for j, ax in enumerate(row):
       ax.imshow(foo[i, j])
fig.show()

Or you can use ravel to flatten the rows and whatever you want to get the data from:

fig, axs = plt.subplots(2, 3)
foor = foo.ravel()
for i, ax in enumerate(axs.ravel()):
    ax.imshow(foor[i])
fig.show()

Note that ravel is a view, not a copy, so this won't take any additional memory.

The key is using the three parameter form of subplot:

import matplotlib.pyplot as plt

# Build a list of pairs for a, b
ab = zip(range(6), range(6))

#iterate through them
for i, (a, b) in enumerate(ab):
    plt.subplot(2, 3, i+1)
    #function(a, b)
    plt.plot(a, b)

plt.show()

You'll just have to take the call to figure out of the function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!