简体   繁体   中英

Clearing graph before replotting matplotlib

I have a little app that allows me to change an input value with a tKinter scale widget and see how a graph reacts to different changes in inputs. Every time I move the scale, it's bound to an event that redoes the calculations for a list and replots. It's kind of slow.

Now, I'm replotting the entire thing, but it's stacking one axis on top of the other, hundreds after a few minutes of use.

deltaPlot = Figure(figsize=(4,3.5), dpi=75, frameon=False)
c = deltaPlot.add_subplot(111)
c.set_title('Delta')
deltaDataPlot = FigureCanvasTkAgg(deltaPlot, master=master)
deltaDataPlot.get_tk_widget().grid(row=0,rowspan=2)

and the main loop runs

c.cla()
c.plot(timeSpread,tdeltas,'g-')
deltaDataPlot.show()

It's clearing the initial plot, but like I said the axes are stacking (because it's redrawing one each time, corresponding to the slightly altered data points). Anyone know a fix?

To improve speed there are a couple of things you could do:

Either Run the remove method on the line produced by plot:

# inside the loop
line, = c.plot(timeSpread,tdeltas,'g-')
deltaDataPlot.show()
...
line.remove()

Or Re-use the line, updating its coordinates appropriately:

# outside the loop
line, = c.plot(timeSpread,tdeltas,'g-')

# inside the loop
deltaDataPlot.show()
line.set_data(timeSpread,tdeltas)

The documentation of Line2d can be found here .

You might also like to read the cookbook article on animation .

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM