【问题标题】:An animation which doesn't work although there is no error [Python]尽管没有错误但不起作用的动画[Python]
【发布时间】:2017-11-25 11:14:47
【问题描述】:

我正在用 Python 编写第二维随机游走。我想动画它如何“成长”。我想使用来自matplotlibanimation.FuncAnimation,但不幸的是它不能如我所愿。但是没有错误,我在 iPython 控制台中使用了%matplotlib tk
我的代码:

def random_walk_animated_2D(n, how_many = 1):

    possible_jumps = np.array([[0, 1], [1, 0], [-1, 0], [0, -1]])
    where_to_go = np.random.randint(4, size = n)
    temp = possible_jumps[where_to_go, :]
    x = np.array([[0, 0]])
    temp1 = np.concatenate((x, temp), axis = 0)
    trajectory = np.cumsum(temp1, axis = 0)

    fig = plt.figure()
    ax = plt.axes(xlim = (np.amin(trajectory, axis = 0)[0], np.amax(trajectory, axis = 0)[0]), 
                  ylim = (np.amin(trajectory, axis = 0)[1], np.amax(trajectory, axis = 0)[1]))
    line, = ax.plot([], [], lw = 2)

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        line.set_data(trajectory[i, 0], trajectory[i, 1])
        return line,

    anim = animation.FuncAnimation(fig, animate, init_func = init, 
                                   frames = 200, interval = 30, blit = True)
    plt.show()

不幸的是,运行该函数后没有任何反应。

稍后我想添加在图中生成多个随机游走的可能性(我的意思是我希望它们同时生成)。我该怎么做?

【问题讨论】:

    标签: python animation matplotlib


    【解决方案1】:

    不可能通过一个点画一条线。
    如果要绘制线图,plot 的参数或线的set_data 方法必须至少有两个点。

    你可能想要的不是line.set_data(trajectory[i, 0], trajectory[i, 1])

    line.set_data(trajectory[:i, 0], trajectory[:i, 1])
    

    绘制一条穿过所有点直到ith 点的线。

    【讨论】:

    • 不幸的是仍然一无所获:(
    • 如果您在更正代码本身时看不到动画,那是因为您丢失了对动画的引用。让你的函数返回动画。在 IPython 中运行时,您不一定需要 plt.show()
    猜你喜欢
    • 2019-11-26
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多