【问题标题】:Animating with matplotlib without animation function用 matplotlib 制作动画,没有动画功能
【发布时间】:2017-06-21 12:08:01
【问题描述】:

有没有一种方法可以在 matplotlib 中为图形制作动画,而无需借助内置动画功能?我发现它们使用起来非常尴尬,并且觉得只绘制一个点,擦除图形,然后绘制下一个点会简单得多。

我的设想是这样的:

def f():
     # do stuff here
     return x, y, t

每个t 将是一个不同的框架。

我的意思是,我尝试过使用plt.clf()plt.close() 等方法,但似乎没有任何效果。

【问题讨论】:

  • 有 fig=plt.figure("animation") im=plt.imshow(M.reshape(lN,lN),interpolation='none') while {some condition}: M=updateFunc () # 更新和改变神经元的电位 im.set_array(M) # 制作图像 fig.canvas.draw() # 绘制图像 plt.pause(0.1) # 减慢“动画”速度

标签: python animation matplotlib


【解决方案1】:

没有FuncAnimation 肯定可以制作动画。然而,“设想的功能”的目的并不是很清楚。在动画中,时间是自变量,即对于每个时间步,您都会生成一些新数据来绘制或类似的。因此该函数会将t 作为输入并返回一些数据。

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    x=np.random.rand(1)
    y=np.random.rand(1)
    return x,y

fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)
for t in range(100):
    x,y = f(t)
    # optionally clear axes and reset limits
    #plt.gca().cla() 
    #ax.set_xlim(0,1)
    #ax.set_ylim(0,1)
    ax.plot(x, y, marker="s")
    ax.set_title(str(t))
    fig.canvas.draw()
    plt.pause(0.1)

plt.show()

此外,尚不清楚您为什么要避免使用FuncAnimation。使用FuncAnimation可以制作与上面相同的动画如下:

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

def f(t):
    x=np.random.rand(1)
    y=np.random.rand(1)
    return x,y

fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)

def update(t):
    x,y = f(t)
    # optionally clear axes and reset limits
    #plt.gca().cla() 
    #ax.set_xlim(0,1)
    #ax.set_ylim(0,1)
    ax.plot(x, y, marker="s")
    ax.set_title(str(t))

ani = matplotlib.animation.FuncAnimation(fig, update, frames=100)
plt.show()

没有太大变化,行数相同,这里没有什么特别尴尬的地方。
此外,当动画变得更复杂、想要重复动画、想要使用位图传输或想要将其导出到文件时,您可以从 FuncAnimation 获得所有好处。

【讨论】:

  • 感谢这个例子。我将其调整为在update 中使用ax.voxels(),但我得到了RuntimeError: The animation function must return a sequence of Artist objects. 我想知道为什么您的代码有效,即使update 没有返回任何内容
  • @crypdick 如果你使用blit=True,你需要返回一个迭代的艺术家来更新。如果您离开blit=False(默认),则不需要这样的列表。
【解决方案2】:

不清楚为什么要避免使用FuncAnimation

对于非常简单的测试,您想在循环深处检查情况,设置animation 函数并不容易。

例如,我想想象一下这种奇怪的排序算法会发生什么:https://arxiv.org/pdf/2110.01111.pdf。在我看来,最简单的方法是:

import numpy as np
import matplotlib.pyplot as plt

def sort(table):
    n = len(table)
    
    for i in range (n):
        for j in range (n):
            if table[i] < table[j]:
                tmp = table[i]
                table[i] = table[j]
                table[j] = tmp
            plt.plot(table, 'ro')
            plt.title(f"i {i} j {j}")
            plt.pause(0.001)
            plt.clf() # clear figure
    return table

n = 50
table =  np.random.randint(1,101,n)
sort(table)
```python

【讨论】:

    【解决方案3】:

    我同意 FuncAnimation 使用起来很尴尬(根本不是 Pythonic)。其实我相信这个功能没有太大意义。拥有它有什么好处?

    是的,它引入了一个您不必自己编写的隐式循环。但是读者不能完全控制这个循环并且——除非他事先知道函数的语法——他甚至无法理解它。出于清晰和多功能的原因,我个人避免使用 FuncAnimation。这是一个最小的伪代码示例:

    fig=plt.figure("animation")
    M=zeros((sizeX,sizeY)) # initialize the data (your image)
    im=plt.imshow(M) # make an initial plot
    ########### RUN THE "ANIMATION" ###########################
    while {some condition}:
        M=yourfunction() # updates your image
        im.set_array(M) # prepare the new image
        fig.canvas.draw() # draw the image
        plt.pause(0.1) # slow down the "animation"
    

    非常简单,您可以看到代码中发生了什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      相关资源
      最近更新 更多