2014-02-21 20 views
2

Thanks to Jake Vanderplas,我知道如何開始使用matplotlib編碼一個動畫圖。下面是一個示例代碼:用matplotlib中的for循環定義多個圖形進行動畫製作

from matplotlib import pyplot as plt 
from matplotlib import animation 

fig = plt.figure() 

ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) 

line, = plt.plot([], []) 

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

def animate(i): 
    line.set_data([0, 2], [0,i]) 
    return line, 

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

plt.show() 

假設現在我想繪製噸的功能(說,四名在這裏),用循環的幫助下定義。我做了一些巫術編程,試圖理解如何模仿逗號後面的行,這是我得到的(不用說,它不起作用:AttributeError: 'tuple' object has no attribute 'axes')。

from matplotlib import pyplot as plt 
from matplotlib import animation 

fig = plt.figure() 

ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) 

line = [] 
N = 4 

for j in range(N): 
    temp, = plt.plot([], []) 
    line.append(temp) 

line = tuple(line) 

def init(): 
    for j in range(N): 
     line[j].set_data([], []) 
    return line, 

def animate(i): 
    for j in range(N): 
     line[j].set_data([0, 2], [10 * j,i]) 
    return line, 

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

plt.show() 

一些我的問題是:我怎樣才能使它發揮作用?獎金(可能已鏈接):line, = plt.plot([], [])line = plt.plot([], [])之間有什麼區別?

感謝

回答

9

首先,我將發佈您的解決方案,然後一些解釋:

from matplotlib import pyplot as plt 
from matplotlib import animation 

fig = plt.figure() 

ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) 

N = 4 
lines = [plt.plot([], [])[0] for _ in range(N)] 

def init():  
    for line in lines: 
     line.set_data([], []) 
    return lines 

def animate(i): 
    for j,line in enumerate(lines): 
     line.set_data([0, 2], [10 * j,i]) 
    return lines 

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

plt.show() 

說明:

  1. line, = plt.plot([], [])分配由plt.plot回到veriable列表中的第一個元素line
  2. line = plt.plot([], [])只分配整個列表(只有一個元素)。

lines = [plt.plot([], [])[0] for _ in range(N)]的替代方法您只能使用一個繪圖命令來執行此操作lines = plt.plot(*([[], []]*N))。我發現第一個更可讀,但是味道的問題。

+0

非常感謝。請問「plt.plot'列表的第一個元素是」什麼「? – cjorssen

+1

'plt.plot'返回'matplotlib.artist.Artist'列表,所以當你只繪製一行時,它會返回一個只包含一個項目的列表:'matplotlib.lines.Line2D'藝術家。但是,如果您在'lines = plt.plot(*([[],[]] * N))中繪製了幾行,則它會返回列表中的所有行。 –

+0

謝謝。最後一個問題。 'animate'的'return'中的'line'後面的逗號不是必需的嗎?如果我正確理解你的解決方案,就不會有這樣的逗號。 – cjorssen