Python脚本:对类中一组线条进行动画化

2024-07-02 14:01:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把matplotlib.animation设置为类函数。虽然我看起来运气不太好。我尝试过这两种方法:functionimation()和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()

我想试着把我的脑子弄清楚,而不是用别人的代码。虽然我是以别人为出发点。有人能帮忙吗?在


Tags: importselfdatamatplotlibinitdefasline
1条回答
网友
1楼 · 发布于 2024-07-02 14:01:49

(警告:这里是新手。)

我认为对于“anim”来说,最好的方法是将其设置为实例变量,使用自我.anim公司名称:

self.anim = ...

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

^{pr2}$

我用的是Spyder2.1.10,虽然动画有点快,但它似乎还在工作。在

相关问题 更多 >