Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
Catherine Georgia Avatar asked Mar 06 '13 17:03

Catherine Georgia


People also ask

How do I stop Matplotlib overlapping?

Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.

What is overlay plot?

Overlay plots are different plots (like vectors and contours) that are drawn on top of each other, and possibly on top of a map. There are many different ways that one can create overlay plots: Use the overlay procedure (this is the best method)

Is PyLab the same as Matplotlib?

PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib. pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib. PyLab is a convenience module that bulk imports matplotlib.


2 Answers

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!

like image 103
danodonovan Avatar answered Oct 05 '22 08:10

danodonovan


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')
like image 22
mechanical_meat Avatar answered Oct 05 '22 08:10

mechanical_meat