Andrea0v0
Andrea0v0

Reputation: 3

How to use matplotlib save multiple plots to a file in loop

x = [1 2 5 6 3 .....]
n = len(x)//34
i = 0
while i < n*34:
    fig, axs = plt.subplots(2)
    axs[0].plot(x[i:34+i],y[i:34+i],x_l[i:34+i],y_l[i:34+i]) #knee
    axs[1].plot(x_a[i:34+i],y_a[i:34+i],color = 'red') #ank
    axs[1].plot(x_l_a[i:34+i],y_l_a[i:34+i],color = 'green')
    axs[0].axis('off')
    axs[1].axis('off')
    plt.savefig('test')
    i = i + 17

The code above will only save the last plot in my file, but I would like to generate and save the multiple plots for different values of i.

Upvotes: 0

Views: 1404

Answers (1)

dspencer
dspencer

Reputation: 4481

Currently, you are overwriting the same "test" file on every iteration; as such, when your program completes, you are left with only the last figure saved to disk. If you want to save multiple files, you need to use a different filename on every iteration in your call to savefig.

For example, you may use the iteration variable i and change your call to:

plt.savefig("test{}".format(i))

Upvotes: 1

Related Questions