rami_salazar
rami_salazar

Reputation: 165

Plot overwriting in for loop

I'm using FeniCS to solve a PDE at different time-steps which I then store into various lists and plot in python using matplotlib. I'm having problems trying to create and save multiple (three) plots in a loop. I can only manage to save one plot without them overwriting. Neglecting necessary details, my code looks like this

for n in range(num_steps):

    #Update current time
    t += dt
    

    #Solve
    solve(a_form == L_form, u)
    
    #Store times
    t_vals.append(t)

    #Solve PDE, gives solution u
    solve(u)

    #Create empty lists
    u_vals_x = []
    u_vals_y = []
    u_vals_z = []

    #Set constant
    xyz_fixed_density = 1000
    #Store u values varying x, y and z held equal to 1
    for n in  np.linspace(x0,x1,xyz_fixed_density):
     u_vals_x.append(u(n,1,1))

     #Store u values varying y, x and z held equal to 1
    for n in  np.linspace(y0,y1,xyz_fixed_density):
     u_vals_y.append(u(1,n,1))


     #Store u values varying z, x and y held equal to 1
    for n in  np.linspace(z0,z1,xyz_fixed_density):
     u_vals_z.append(u(1,1,n))
    
    #First plot
    plt.scatter(np.linspace(x0,x1,xyz_fixed_density),u_vals_x,s=1)
    plt.legend(t_vals)
    plt.xlabel('$x$')
    plt.ylabel('$u(t,x,1,1)$')
    plt.savefig('u_vs_x.png')
    
    #Second plot
    plt.scatter(np.linspace(y0,y1,xyz_fixed_density),u_vals_y,s=1)
    plt.legend(t_vals)
    plt.xlabel('$y$')
    plt.ylabel('$u(t,1,y,1)$')
    plt.savefig('u_vs_y.png')
    
    #Third plot
    plt.scatter(np.linspace(z0,z1,xyz_fixed_density),u_vals_z,s=1)
    plt.legend(t_vals)
    plt.xlabel('$z$')
    plt.ylabel('$u(t,1,1,z)$')
    plt.savefig('u_vs_z.png')

It's probably a simple fix but I can't seem to get it to work. Thanks in advance.

Upvotes: 0

Views: 1146

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Use the current iteration (n) as part of the filenames; e.g. replace

plt.savefig('u_vs_x.png')

with

plt.savefig(f'u_vs_x_{n}.png')

This uses the f-string syntax to format the code. If you’re using an older Python version which does not support f-strings yet, use format explicitly:

plt.savefig('u_vs_x_{}.png'.format(n))

You’ll also need to create a new plot each time, e.g. via

plt.figure()

Upvotes: 2

Related Questions