我不能保存动画

2024-04-19 18:45:40 发布

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

我试过各种各样的例子,虽然我找不到合适的解决办法。这是我的项目的示例代码,我想将其保存为mp4格式,并使用ffmpeg。如对此有任何建议,将不胜感激。先谢谢你

import pandas as pd
import numpy as np
import ma``tplotlib.pyplot as plt
import matplotlib.animation as animation

df = data.iloc[0:250, 4:12]
df1 = df2.iloc[:,0:3]

a1 = df.iloc[:,0]/2
a2 = df.iloc[:,1]/2
b1 = df.iloc[:,2]/2
b2 = df.iloc[:,3]/2
c1 = df.iloc[:,4]/2
c2 = df.iloc[:,5]/2
m1 = df1.iloc[:,0]
m2 = df1.iloc[:,1]
m3 = df1.iloc[:,2]

fig ,ax = plt.subplots()

l1, = ax.plot (vert1, vert2, 'ro', markersize = m1[0])
l2, = ax.plot (long1, long2, 'ro', markersize = m2[0])
l3, = ax.plot (tras1, tras2, 'ro', markersize = m3[0])

def init():    
    l1.set_data([],[])
    l2.set_data([],[])
    l3.set_data([],[])
    
    return (l1,l2,l3)

def animate(i,l1,l2,l3):
    
    l1.set_data(vert1[i], vert2[i])
    l1.set_markersize(m1[i])
    l2.set_data(long1[i], long2[i])
    l2.set_markersize(m2[i])
    l3.set_data(tras1[i], tras2[i])
    l3.set_markersize(m3[i])

    return (l1,l2,l3)

Writer = animation.writers['ffmpeg']
writer = Writer(fps= 100, metadata = dict(artist = 'me'), bitrate = 1800)

ani = animation.FuncAnimation(fig, animate, fargs=(l1,l2,l3), init_func=init, interval=10, blit=False)
ani.save('/Users/gokulthangavel/Downloads/basic_animation.mp4', writer = writer)

plt.show()

Tags: importl1dfdataaspltaxdf1
1条回答
网友
1楼 · 发布于 2024-04-19 18:45:40

代码看起来是正确的

我试图用合成数据(sincos)来重现这个问题——替换您没有发布的数据

我修改了一些参数:

  • 将fps从fps=100减少到fps=10(100 fps太快)
  • 添加一个参数frames=200,用于创建具有200帧的动画

如果我不得不猜测,您的问题与输入数据(未列出的数据)有关。
可能是数据点超出了轴限制,并且所有数据点都在轴之外(或其他类似问题)

也可能是间隔太大或动画太长


根据文档,您似乎需要返回轴:

return ax

但是return (l1, l2, l3)起作用(返回值被忽略)


以下是您的代码的修改版本:

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

fig ,ax = plt.subplots()

fig.set_size_inches(4, 3)  # Reduce size of Stack Overflow posting.

l1, = ax.plot (np.arange(1, 10), np.arange(1, 10), **{'marker':'o'})
l2, = ax.plot (np.arange(1, 10), np.arange(1, 10), **{'marker':'o'})
l3, = ax.plot (np.arange(1, 10), np.arange(1, 10), **{'marker':'o'})

def init():
    l1.set_data([],[])
    l2.set_data([],[])
    l3.set_data([],[])
    
    return (l1, l2, l3)

def animate(i, l1, l2, l3):
    l1.set_data(i/22, np.sin(0.1*i)*4+5)
    l1.set_markersize(4)
    l2.set_data(i/22, np.cos(0.01*i*i)*4+5)
    l2.set_markersize(5)
    l3.set_data(9-i/22, (-np.cos(0.1*i))*4+5)
    l3.set_markersize(6)
 
    # return ax
    return (l1, l2, l3)

Writer = animation.writers['ffmpeg']
writer = Writer(fps=10, metadata=dict(artist = 'me'), bitrate=1800)

ani = animation.FuncAnimation(fig, animate, fargs=(l1,l2,l3), init_func=init, frames=200, interval=1, blit=False)  # 200 frames, interval=1
#ani.save('basic_animation.mp4', writer=writer)
ani.save('basic_animation.gif', writer=writer)  # Create animated gif (instead of mp4) for Stack Overflow posting.

plt.show()

结果:
animation

相关问题 更多 >