Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 764
Reza Hashemi Avatar asked Sep 26 '17 04:09

Reza Hashemi


1 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)
like image 154
Paul H Avatar answered Oct 08 '22 18:10

Paul H