Python脚本,用于为类中的一组行设置动画

时间:2013-11-12 12:55:10

标签: python animation matplotlib

我试图将matplotlib.animation设置为类函数。虽然我似乎没有太多运气。我试过了两个,FunctionAnimation()& ArtistAnimation()。对于这两者我似乎无法让他们工作(虽然他们是非常不同的)。

# ------------------------------ #
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# ------------------------------ #
class AniPlot():
    def __init__(self):
        self.fig = plt.figure()
        self.ax = plt.axes(xlim=(-3.5, 3.5), ylim=(-5, 2))
        self.line, = self.ax.plot([], [], lw=2)


    def set_data(self,tvector):
        self.data = tvector

    def ani_init(self):
        self.line.set_data([], [])

    def ani_update(i):
        x = self.data[i][0]
        y = self.data[i][1]

        self.line.set_data(x, y)
        return self.line,


    def animate(self):
        anim = animation.FuncAnimation(self.fig, self.ani_update, init_func=self.ani_init,
                               frames=4, interval=20, blit=True)
        plt.show()

# ------------------------------ #

data = [
[[0,0,1,0],[0,-1,-2,-3]],
[[0,0,0,0.1],[0,-1,-3,-4]],
[[0,0,0.5,0],[0,-1,-2.5,-3.5]],
[[0,0,1,2],[0,-1,-2,-2.5]]
        ]
myani = AniPlot()
myani.set_data(data)
myani.animate()

我想尝试解决它,而不是使用别人的代码。虽然我确实以别人为出发点。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

(警告:新手在这里。)

我认为“动画”坚持的最佳方式实际上是使用self.anim将其设置为实例变量:

self.anim = ...

你还需要在这里添加“self”:

def ani_update(self, i)

我使用Spyder 2.1.10并且它看起来很有效,虽然动画有点快。

答案 1 :(得分:1)

您可以将 blit 设置为 False 或 True,但请确保将 return self.line 行替换为 return self.line,

#!/usr/bin/env python3

# ------------------------------ #
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# ------------------------------ #
class AniPlot():
    
    def __init__(self):
        self.fig = plt.figure()
        self.ax = plt.axes(xlim=(-3.5, 3.5), ylim=(-5, 2))
        self.line, = self.ax.plot([], [], lw=2)


    def set_data(self,data):
        self.data = data

    def ani_init(self):
        self.line.set_data([], [])
        return self.line

    def ani_update(self, i):
        x = self.data[i][0]
        y = self.data[i][1]
        self.line.set_data(x, y)
        return self.line


    def animate(self):
        self.anim = animation.FuncAnimation(self.fig, self.ani_update, init_func=self.ani_init, frames=4, interval=20, blit=False)
        plt.show()

# ------------------------------ #

data = [
[[0,0,1,0],[0,-1,-2,-3]],
[[0,0,0,0.1],[0,-1,-3,-4]],
[[0,0,0.5,0],[0,-1,-2.5,-3.5]],
[[0,0,1,2],[0,-1,-2,-2.5]]
        ]
myani = AniPlot()
myani.set_data(data)
myani.animate()