0

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()  
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • Define the title and labels before the loop then set them again? – wwii Dec 09 '22 at 15:46
  • Does [Matplotlib - How to remove a specific line or curve](https://stackoverflow.com/questions/19569052/matplotlib-how-to-remove-a-specific-line-or-curve) answer your question? – wwii Dec 09 '22 at 15:52
  • How about [Delete lines in matplotlib](https://stackoverflow.com/questions/2732578/delete-lines-in-matplotlib)? – wwii Dec 09 '22 at 16:11
  • https://stackoverflow.com/a/9896338/2823755 – wwii Dec 09 '22 at 16:36

2 Answers2

0

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()  
0

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()
wwii
  • 23,232
  • 7
  • 37
  • 77