matplotlib中的动画图,包含来自循环的数据

时间:2015-03-29 00:00:46

标签: python animation matplotlib

我从matplotlib制作了一个动画程序,遵循程序代码:

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

def fung(y,v,t,w,g,A):
    import numpy as np
    return -g*v - np.sin(y) + A*np.sin(w*t)

datax = []
datay = []
fig = plt.figure()
ax = plt.axes(xlim=(0,200), ylim=(-20,20))
line, = ax.plot([], [], '-')

g = 0.2
A = 2
w = np.pi*0.1
y0 = 0.0
v0 = 0.0
dt = 0.1
t0 = 0.0
for i in range (10000):
    t = t0 +dt
    y = y0 +dt*v0
    v = v0 + dt*fung(y0,v0,t0,w,g,A)
    t0 = t
    v0 = v
    y0 = y
    datax.append(t0)
    datay.append(y0)

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

def animate(i):
    line.set_ydata(datay[i])
    line.set_xdata(datax[i])
    return line,

anim = animation.FuncAnimation(fig, animate, interval=50, blit=True)

plt.show()

编译后,在matplotlib图中没有描绘图形。

愿任何人给我一些提示吗?

我非常赞赏

2 个答案:

答案 0 :(得分:0)

当您说:您正在设置单点数据时:

line.set_ydata(datay[i])
line.set_xdata(datax[i])

line.set_ydata(datay[i]) line.set_xdata(datax[i])

所以这是结果代码:

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

def fung(y,v,t,w,g,A):
    return -g*v - np.sin(y) + A*np.sin(w*t)

datax = []
datay = []
fig = plt.figure()
ax = plt.axes(xlim=(0,200), ylim=(-50,50))
line, = ax.plot(datax, datay, '-')

g = 0.2
A = 2
w = np.pi*0.1
y0 = 0.0
v0 = 0.0
dt = 0.1
t0 = 0.0
for i in range (10000):
    t = t0 +dt
    y = y0 +dt*v0
    v = v0 + dt*fung(y0,v0,t0,w,g,A)
    t0 = t
    v0 = v
    y0 = y
    datax.append(t0)
    datay.append(y0)

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

def animate(i):
    line.set_ydata(datay)
    line.set_xdata(datax)
    return line,

anim = animation.FuncAnimation(fig, animate, interval=50, blit=True)

plt.show()

答案 1 :(得分:0)

设置ylim=(-10,40)ylim=(-40,40)或图表的一半是不可见的。要逐步构建图表,请使用animate(i):

line.set_ydata(datay[:i])
line.set_xdata(datax[:i])

显示索引i-1之前的所有点。

您可能希望使用interval=10或一次性将显示增加5点来提高速度,

line.set_ydata(datay[:5*i])
line.set_xdata(datax[:5*i])

有趣和利润集interval=5并使用

line.set_ydata(datay[i-10:i])
line.set_xdata(datax[i-10:i])