Matplotlib savefig() over multiple graphs keeps saving the same graph

Viewed 26823

So I have a function generategraph(file) which correctly creates a bar graph based on the data in the parameter and then saves it. Here is the part that saves it.

    plt.show()
    savefile = file.split('.txt')[0] + '.png'
    plt.savefig(savefile)

then in main, I will go through a set of files and call generategraph on each one.

    for fil in files:
        generategraph(fil)

plt.show() gives me the correct graphs (different graphs each time), but when I go to the saved figures they are all of the same graph (so len(files) number of saved figures but each one is the graph of the first file if that makes sense). I am just confused because plt.show() is doing what I want plt.savefig to do.

2 Answers

You're using the state-machine (pyplot) interface. Don't.

Create your figures explicitly:

fig1, ax1 = pyplot.subplots()

Act on them directly:

lines, = ax1.plot(data1, data2, ...)

Then save and close them individually:

fig1.savefig(filename, dpi=300)
pyplot.close(fig1)

You probably need to verify that the name of the figure you save is different for each. (The following is pseudocode, it is not clear how you get the file name.)

[edit] Then you probably should place plt.show() after plt.savefig(savefile)

#initialize idx to 0 earlier, and don't re-initialize it.

idx += 1
savefile = file + str(idx) + '.png'   # file might need to be replaced by a string
plt.savefig(savefile)
plt.show()              # place after plt.savefig()

Alternatively, you change the signature of generategraph

def generategraph(file, idx):
    savefile = file + str(idx) + '.png'  # file might need to be replaced by a string
    plt.savefig(savefile)
    plt.show()              # place after plt.savefig()



for idx, fil in enumerate(files):
    generategraph(fil, idx)
Related