4

我正在尝试将 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()

我想尝试一下,而不是使用别人的代码。尽管我确实以其他人为起点。任何人都可以帮忙吗?

4

2 回答 2

3

(警告:这里是新手。)

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

self.anim = ...

您还需要在此处添加“self”:

def ani_update(self, i)

我使用 Spyder 2.1.10,它似乎可以工作,虽然动画有点快。

于 2013-11-12T13:23:46.087 回答
1

您可以将 blit 设置为 False,也可以设置为 True,但请确保将行替换return self.linereturn 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()
于 2021-04-10T00:15:22.370 回答