简体   繁体   中英

matplotlib scatter animation; original plot always on screen

My animation is not working as expected:

With blit = True I have the original function on screen always and without it I have every update of the function, neither of which is desirable.

Any help greatly appreciated, Im using Anaconda collection of SciPy packages on Win7 with spyder IDE

I've tried playing with the arguments in animation.FuncAnimation() but no luck, I've bare boned the code.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation



def run():

    x = range(100)
    y = range(0, 1000, 10)
    x2 = range(50)
    y2 =range(0, 500, 10)
    fig = plt.figure()
    scat1 = plt.scatter(x, y)


    ani = animation.FuncAnimation(fig, update_plot, blit = True)
    plt.show()

def update_plot(i):
    x = range(i, 100+i)
    y = range(i, 1000+i, 10)
    scat1 = plt.scatter(x,y)


    return scat1,


run()

Setting an init function is required "to set a clean slate" :

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

def run():
    fig = plt.figure()
    pathcol = plt.scatter([], [])

    def init():
        pathcol.set_offsets([[], []])
        return [pathcol]

    def update_plot(i, pathcol):
        x = range(i, 100+i)
        y = range(i, 1000+i, 10)
        pathcol.set_offsets([(xi, yi) for xi, yi in zip(x, y)])
        return [pathcol]

    plt.xlim(-10, 200)
    plt.ylim(-100, 1500)
    ani = animation.FuncAnimation(fig, update_plot, 
                                  init_func=init, 
                                  interval=0,
                                  blit=True, fargs=[pathcol])
    plt.show()

run()
  • Also, inside update_plot be sure to use pathcol.set_offsets to modify the existing PathCollection instead of calling plt.scatter again. Modifying the existing Artist will improve animation speed.

  • init does not take any arguments, but we want init to refer to the pathcol created in run . Therefore I moved init inside the run function so that inside init Python will find pathcol in the enclosing scope of run .

  • update_plot is passed pathcol since fargs=[pathcol] , so update_plot could be made a function outside of run . But since init is nested inside run , for symmetry I decided to put update_plot inside run too.

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