2017-09-16 36 views
0

我是新来的编码,并试图从以前生成的代码在八度(下)中创建一个python动画。到目前为止,我还没有取得任何成功,除了绘制一个无生气的散点图。任何提示或帮助将不胜感激。从Octave代码创建动画python

clear; 

    N = 100; 
    NT = 200; 

    for i=1:N 
     x(i) = 0; 
     y(i) = 0; 
    end 

    plot(x,y,'o'); 
    axis([0 20 -10 10]); 

    for k = 1 : NT 
     x = x + normrnd(0.1,0.1,1,N); 
     y = y + normrnd(0,0.1,1,N); 
     temp = mod(k,1); 
     if temp == 0 

      plot(x,y,'s'); 
      axis([0 20 -10 10]); 
      drawnow 

     end 
    end 

以下是许多未尝试的尝试之一(下)。

import numpy as np 
    import matplotlib as plt 
    from pylab import * 
    from matplotlib import animation 
    import random 

    n=100 
    nt=2000 
    m=20 
    mu=0 
    sigma=0.1 
    p=100 

    fig = plt.figure() 
    ax = plt.axes(xlim=(-10, 10), ylim=(-10, 10)) 
    scat, = ax.plot([], []) 

    # initialization function: plot the background of each frame 
    def init(): 
      x = 0 
      y = 0 
      return scat, 

    # animation function. This is called sequentially 
    def animate(i): 
     for k in range (1,nt): 
      x = x+ np.random.normal(mu, sigma, n) 
      return scat, 

     for i in range (1,nt): 
      y = y+ np.random.normal(mu, sigma, n) 
      return scat, 

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

    plt.show() 

回答

0

你可以用Python的Octave做动画。

对于Python脚本,我认为其中一个问题是在一个循环内设置一个返回值,因此对于一个函数def animate来说需要多次。纵观动画DOC https://matplotlib.org/api/animation_api.html我编辑你的榜样,并得到了这个,我认为可能是有用的:

import numpy as np 
import matplotlib.pyplot as plt 
from pylab import * 
from matplotlib.animation import FuncAnimation 
import random 

n=100 
sigma=0.1 
nt=2000 

fig, ax = plt.subplots() 
xdata, ydata = [0.0], [0.0] 
ln, = plt.plot([], [], 'ro', animated=True) 

def init(): 
    ax.set_xlim( 0, 20) 
    ax.set_ylim(-10, 10) 
    return ln, 

def update(frame): 
    global xdata 
    global ydata 
    xdata = xdata + np.random.normal(0.1, sigma, n) 
    ydata = ydata + np.random.normal(0.0, sigma, n) 
    ln.set_data(xdata, ydata) 
    return ln, 

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), 
        init_func=init, blit=True) 
plt.show() 

你也不要使用八度的打印命令生成几个PNG图像,并使用GIMP的动画制作GIF或embbed在LaTeX中使用动画的pngs。

最好, 豪尔赫

+0

谢谢豪尔赫!有没有办法建立一个“地板”,粒子在到达指定位置后停止? – lake08