Home > Software design >  How to clear the current figure in matplotlib?
How to clear the current figure in matplotlib?

Time:02-14

The code snippet is given below. I want to save a new figure at each iteration of the loop. But, the original figure is overwritten instead of creating a new one. I have used plt.cla(), plt.clf(). but could not get the desired result.

for i in range(17)
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))
        
plt.savefig(f"{output_dir}/{counter}.png")
counter  = 1
plt.clf()

CodePudding user response:

So it seems like what is going on is, everytime you plot, you are plotting onto the same "canvas". To create a new canvas for each iteration of your for loop, you can use plt.figure(i) argument which creates a new cavanas with the unique ID variable "i".

Now, plt.savefig will save the canvas created by the most recent plt.figure(i) argument. So basically, what you want to do is sandwich your plotting code with plt.figure(i) and plt.savefig("name.png") but assigning a new "i" value each time.

for i in range(17):
    plt.figure(i)
    ...insert plotting code e.g. plt.scatter(x_coord, y_coord, color = 'red')...
    plt.savefig("name of ith figure.png")

CodePudding user response:

It worked for me with minor changes. It seems you have just to move some statements WITHIN the loop. I run your code with these minor changes:

  1. created simple series
  2. initialised the "counter"
  3. I just used the current directory (no path).

This is the code:

import matplotlib
import matplotlib.pyplot as plt
x_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
y_coord = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
counter = 1

for i in range(17):

    fig, ax = plt.subplots()
    ax.scatter(x_coord, y_coord, color = 'red')
    ax.text(x_coord[i], y_coord[i], str(i))
    plt.savefig(f"{counter}.png")
    counter  = 1
    plt.clf()
#end
  • Related