I have a class which I use to plot things then save them to a file. Here’s a simplified version of it:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, 'D', color='red')
ax.set_xbound(-5,5)
ax.set_ybound(-5,5)
plt.savefig('%s.png' % filename)
test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')
Here are the results:
test1

test2

The problem is that the test2 image also has the point from test1. The graphs are generated dynamically in a loop so I can’t hardcode the figure number.
I could make a counter and pass it to the class constructor but I was wondering if there’s a more elegant way to do this. I tried deleting the test1 object but that didn’t do anything.
You could use the figure’s clf method to clear the figure after you’re done with one. Also, pyplot.clf will clear the current figure.
Alternatively, if you just want a new figure then call pyplot.figure without an explicit
numargument — it will autoincrement, so you don’t need to keep a counter.