Looping through a function to plot several subplots, Python

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

I have variables x and y

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

    # perform some fitting          


        
相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2021-01-15 08:19

    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.

    0 讨论(0)
提交回复
热议问题