Search code examples
pythonloopsmatplotlibpng

How to save multiple plots as seperate png files with names in Python?


I have code which looks something like this:

a = datetime(2019, 1, 22) #Key dates area
b = datetime(2019, 1, 23)

for _, d in df.set_index('Date').groupby('Country'):
    fig, ax = plt.subplots()
    d['Counts'].plot()
    plt.axhline(y=d['Counts'].mean(), color='r', linestyle='--')
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Country'].iat[0]}")
    plt.xlabel('Week')


    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    plt.show()

I'm hoping to save every graph returned from this loop as separate png files where the name of the image is based on the country being represented within the graph. Is there a way to do this?

Thank you :)


Solution

  • What you are looking for is plt.savefig which saves the current figure. You can add it into the loop before showing or instead of showing the plot:

    # ...
    plt.legend()
    plt.savefig(f"{d['Country'].iat[0]}_plot.png")
    # ...
    

    and it should save in the current directory the plots generated in the loop.