3

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.

1 Answer 1

10

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 num argument -- it will autoincrement, so you don't need to keep a counter.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked great. Thank you. I just needed a new figure so I left out the num argument. I didn't know I could do that until now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.