python - 使用不带动画功能的 matplotlib 进行动画处理

标签 python animation matplotlib

有没有一种方法可以在 matplotlib 中对图形进行动画处理,而无需借助内置的动画函数?我发现它们使用起来非常尴尬,并且觉得只绘制一个点,删除图表,然后绘制下一个点会简单得多。

我设想的东西是这样的:

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

其中每个t都是不同的帧。

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

最佳答案

不用 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的所有好处。当动画变得更加复杂时、当您想要重复动画时、当您想要使用位 block 传送时或者当您想要将其导出到文件时。

关于python - 使用不带动画功能的 matplotlib 进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035779/

相关文章:

python-3.x - PathCollection' 对象没有属性 legend_elements''

python - 根据另一个 df 中的值填充新的 pandas df

python - 如何防止Python中的特殊字符自动转义

jsf - PrimeFaces 状态栏是静态的而不是动画的

java - 启动位图

ios - UIView AnimateWithDuration 处理速度很快

python - 在两个单独的一维图之间绘制连接点的线

python - Matplotlib 散点图过滤器颜色(Colorbar)

python - 在图像上用 Python 实现 Kruskal 算法

python - 如何切换到 IPython 创建的 python 子进程(在 OS X 上)?