Saving figures in a loop in matplotlib

53 views Asked by At

I am trying to save multiple histograms while iterating through a loop but it just ends up saving as a blank image. I tried the exact same code outside the loop and it seems to work, so I'm not sure why it's not working in the loop.

This is what I have right now

for x in range(len(7)):
    plt.figure(figsize = (10, 6))
    hist, bins, patches = plt.hist(list[x], 100)
    plt.title('pol frac reg '+ str(x))
    plt.show()
    plt.savefig('pol_frac_' + str(x))
1

There are 1 answers

0
Florent Monin On BEST ANSWER

When you show an image, it clears it afterwards. As explained in the Matplotlib documentation:

If you want an image file as well as a user interface window, use pyplot.savefig before pyplot.show. At the end of (a blocking) show() the figure is closed and thus unregistered from pyplot. Calling pyplot.savefig afterwards would save a new and thus empty figure.

Try to save first, and then show:

for x in range(len(7)):
    plt.figure(figsize = (10, 6))
    hist, bins, patches = plt.hist(list[x], 100)
    plt.title('pol frac reg '+ str(x))
    plt.savefig('pol_frac_' + str(x))
    plt.show()