Catherine Georgia
Catherine Georgia

Reputation: 969

Stop pylab overlaying plots?

In my code, I am trying to periodically create a graph and save the graph to a file. The code looks like this:

import pylab as p

def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    p.hist(data)
    p.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')

(a is a counter)

However, doing this means that each new plot that is created, keeps being overlayed onto the plots before. How can I let it know that once I have saved the figure, I want it to start a new figure?

Upvotes: 6

Views: 8731

Answers (3)

tacaswell
tacaswell

Reputation: 87376

You can also, just turn hold off (doc)

import pylab as p
ax = p.gca()
ax.hold(False)

def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    ax.hist(data)
    ax.figure.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')

which will clear the axes for you when ever you add a new plot.

If you have a bunch of other artists, and only want to remove the most recent one, you can use the remove instance functoin of artists.

import pylab as p
ax = p.gca()
# draw a bunch of stuff onto the axse

def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    n, bins, h_art = ax.hist(data)
    ax.figure.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')
    for ha in h_art:
        h_a.remove()
    # ax.figure.canvas.draw() # you might need this

Upvotes: 2

danodonovan
danodonovan

Reputation: 20343

To clear the plot use p.clf

def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    p.clf()
    p.hist(data)
    p.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')

presuming that p is a matplotlib.pyplot or figure instance, also what @bernie says - that would work fine too.

@Yann's Comment

If you've already set up your title, axis labels etc then this will nuke all those settings. Better would be to do as he says and try

 p.gca().cla()

to preserve your hard work. Thanks Yann!

Upvotes: 9

mechanical_meat
mechanical_meat

Reputation: 169324

Edit: danodonovan's answer is most likely preferable to this one from a performance standpoint.


You don't show how p is created, but I presume it is something like:

import matplotlib.pyplot as plt
p = plt.figure()

In which case you'd just need to make sure you create a new figure each time. Example:

def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    p = plt.figure() # let's have a new figure why don't we 
    p.hist(data)
    p.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')

Upvotes: 2

Related Questions