Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: plot multiple graphs using same figure, without them overlapping

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.

like image 467
Virgiliu Avatar asked May 19 '26 07:05

Virgiliu


1 Answers

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.

like image 103
ars Avatar answered May 20 '26 20:05

ars