2015-11-03 179 views
0

在下面的例子中,我想製作一個動畫,其中一個點在T秒內圍繞一個圓移動(例如T = 10)。然而它慢得多,不起作用。那麼,我的代碼有什麼問題以及如何解決它?據我瞭解api(http://matplotlib.org/api/animation_api.html)設置interval=1應更新數字每毫秒。Matplotlib實時動畫

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

R = 3 
T = 10 

fig = plt.figure() 
fig.set_dpi(300) 
fig.set_size_inches(7, 6.5) 

ax = plt.axes(xlim=(-10, 10), ylim=(-R*1.5, R*1.5)) 
ax.set_aspect('equal') 


patch = plt.Circle((0, 0), 0.1, fc='r') 
looping = plt.Circle((0,0),R,color='b',fill=False) 
ax.add_artist(looping) 
time_text = ax.text(-10,R*1.2,'',fontsize=15) 

def init(): 
    time_text.set_text('') 
    patch.center = (0, 0) 
    ax.add_patch(patch) 
    return patch,time_text, 


def animate(i): 
    t=i/1000.0 
    time_text.set_text(t) 
    x, y = patch.center 
    x = R*np.sin(t/T*2*np.pi) 
    y = R*np.cos(t/T*2*np.pi) 
    patch.center = (x, y) 
    return patch,time_text 

slow_motion_factor=1 

anim = animation.FuncAnimation(fig, animate, 
           init_func=init, 
           frames=10000, 
           interval=1*slow_motion_factor, 
           blit=True) 

plt.show() 

我應該補充一點,問題取決於運行程序的機器。例如,在舊的英特爾雙核(P8700)(這是程序運行的盒子)上,這比在新的i7桌面cpu上慢很多。但在後一種情況下,它的速度也要慢得多。

+0

的'interval'參數指定了* *最小幀之間的時間間隔。您可以增加它以獲得更一致(但較慢)的幀速率,但減小它並不會讓您的動畫渲染速度更快。實際上,每幀幾乎肯定會花費超過一毫秒的時間來呈現,因此您所看到的是兩臺機器可以管理的最大幀率之間的差異。 –

+0

如果機器在1ms內無法提供新的繪圖,那麼動畫如何在1 ms內更新?這並不成功。找到您的機器可以使用和使用它的時間間隔。 O(100 Hz)間隔的通常監測速率比10 ms更快,這沒有意義。我會選擇40像素來獲得每秒25幀。 – MaxNoe

回答

1

問題是,您的計算機速度不夠快,每隔1毫秒發送一個新圖像。這是預料之中的。

你應該去一個更現實的速度。每秒25幀應該足夠 並且也可以及時渲染。

我還對你的代碼做了一些調整,主要是樣式和更多的語義變量名。 最大的變化是適應這個答案對你的代碼擺脫第一幀是在初始化後,仍然存在的: Matplotlib animation: first frame remains in canvas when using blit

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

R = 3 
T = 10 
time = 3 * T 
slow_motion_factor = 1 
fps = 50 
interval = 1/fps 

fig = plt.figure(figsize=(7.2, 7.2)) 
ax = fig.add_subplot(1, 1, 1, aspect='equal') 
ax.set_xlim(-1.5 * R, 1.5 * R) 
ax.set_ylim(-1.5 * R, 1.5 * R) 

runner = plt.Circle((0, 0), 0.1, fc='r') 
circle = plt.Circle((0, 0), R, color='b', fill=False) 
ax.add_artist(circle) 
time_text = ax.text(1.1 * R, 1.1 * R,'', fontsize=15) 

def init(): 
    time_text.set_text('') 
    return time_text, 


def animate(i): 
    if i == 0: 
     ax.add_patch(runner) 
    t = i * interval 
    time_text.set_text('{:1.2f}'.format(t)) 
    x = R * np.sin(2 * np.pi * t/T) 
    y = R * np.cos(2 * np.pi * t/T) 
    runner.center = (x, y) 
    return runner, time_text 

anim = animation.FuncAnimation(
    fig, 
    animate, 
    init_func=init, 
    frames=time * fps, 
    interval=1000 * interval * slow_motion_factor, 
    blit=True, 
) 

plt.show() 
+0

謝謝,現在它更流暢,運行速度更快。但現在它似乎跑得太快。我不僅想要一個流暢的動畫,而且還需要一個實時的動畫。例如,如果我將T更改爲60並使用秒錶,則似乎需要40秒才能執行一次。順便說一下,它使用python3運行,但不使用python2運行。 – student

+0

'from __future__ import division'應該修復python2。 (T/T = 0) – MaxNoe