Looping through a function to plot several subplots, Python

前端 未结 2 1965
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 07:58

I have variables x and y

def function(a,b):
    x = x[(x>a)*(xb)]

    # perform some fitting          


        
2条回答
  •  -上瘾入骨i
    2021-01-15 08:16

    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.

提交回复
热议问题