Home > Enterprise >  Python plotting clearing the graph in for loop
Python plotting clearing the graph in for loop

Time:12-10

I am plotting within a for loop. So that I get a new graph each iteration. Of course I want to clear the graph from the previous iteration. When I use plt.cla() the axis labels and title is also cleared. How can I just remove the graph but keep the axis labels and title?

for n in range(N):
    ax.plot(x[n],t) # plot  
    plt.savefig(f'fig_{n}.png') # save the plot
    plt.cla()  

CodePudding user response:

Try plt.clf() - clear figure

for n in range(N):
    ax.plot(x[n],t) # plot  
    plt.savefig(f'fig_{n}.png') # save the plot
    plt.clf()  

CodePudding user response:

Remove lines at the bottom of the loop.

from matplotlib import pyplot as plt
import numpy as np

y = np.arange(10)
fig,ax = plt.subplots()
ax.set_title('foo')
ax.set_ylabel('wye')
ax.set_xlabel('EX')

for n in range(3):
    ln, = ax.plot(y*n)
    fig.savefig(f'fig{n}')
    ln.remove()
  • Related