Matplotlib plot only makes final plot in loop

Question:

In my code I have multiple plots I want to automate, I use a for loop to run through code and create 1 plot per loop. However the code seems to only create the final plot. This seems to work if I call the function in a loop but I don’t understand why it wouldn’t create all the plots the way I do it here.

for i in range(num_x):
        curr = usehdr[xcols[i]]

        for j in range(num_y):
            domain = data[:,xcols[i] - 1]
            image  = data[:,ycols[j] - 1]
            plt.plot(domain,image,'.', color = 'black')
            plt.xlabel(curr + ' NN distances (Mpc)')
            plt.ylabel(usehdr[ycols[j]])
            plt.title('D4000_N vs NN distances')

the i variable is the amount of plots where the x data set is changed
the j variable is the amount of plots where the y data set is change. Usually i goes from 0 to 9 inclusive and j executes only once.

Asked By: QuantumPanda

||

Answers:

I fixed it, figured out it is very similar to MATLAB and I needed to implement subplot to retain my other plots. Now this code works:

for i in range(num_x):
    curr = usehdr[xcols[i]]
    
    for j in range(num_y):
        domain = data[:,xcols[i] - 1]
        image  = data[:,ycols[j] - 1]
        plt.subplot(num_x,num_y,i+1)
        plt.plot(domain,image,'.', color = 'black')
        plt.xlabel(curr + ' NN distances (Mpc)')
        plt.ylabel(usehdr[ycols[j]])
        plt.title('D4000_N vs NN distances')

or alternatively, using plt.show() for several separate plots.

for i in range(num_x):
    curr = usehdr[xcols[i]]
    
    for j in range(num_y):
        domain = data[:,xcols[i] - 1]
        image  = data[:,ycols[j] - 1]
        plt.plot(domain,image,'.', color = 'black')
        plt.xlabel(curr + ' NN distances (Mpc)')
        plt.ylabel(usehdr[ycols[j]])
        plt.title('D4000_N vs NN distances')
        plt.show()
Answered By: QuantumPanda