pythonpython-3.xloopsmatplotlibsavefig

Saving figures in a loop in matplotlib


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))

Solution

  • 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()