2017-09-16 94 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