2017-08-04 45 views
0

我跟着回答以下問題定義多個情節在matplotlib動畫陣列和更新對象

Defining multiple plots to be animated with a for loop in matplotlib

答案定義並繪製線條,但我想在繪製和更新點動畫。我修改了代碼並試圖繪製點。當我運行代碼時,它顯示空白圖形,繪製任何東西。

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

fig = plt.figure() 

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

N = 4 
points = ax.plot(*([[], []]*N)) 

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

def animate(i): 
    # for j,line in enumerate(lines): 
    # print j,i 
    #  line.set_data([0,j], [2,i]) 
    points[0].set_data([[0],[i]]) 
    points[1].set_data([[1],[i+1]]) 
    points[2].set_data([[2],[i+2]]) 
    points[3].set_data([[3],[i+3]]) 
    return points 

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

plt.show() 

我該如何解決這個問題?

由於

回答

0

set_data()函數需要至少2個元素的列表,因爲它繪製一條線。

例如:

def animate(i): 
    points[0].set_data([[0, 1],[i, i+1]]) 
    points[1].set_data([[1, 2],[i+1, i+2]]) 
    points[2].set_data([[2, 3],[i+2, i+3]]) 
    points[3].set_data([[3, 4],[i+3, i+4]]) 
    return points 

這是使點僅可見必要,在我們把一個標記:

points = ax.plot(*([[], []]*N), marker="o") 

完整代碼:

fig = plt.figure() 

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

N = 4 
points = ax.plot(*([[], []]*N), marker="o") 

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

def animate(i): 
    points[0].set_data([0],[i]) 
    points[1].set_data([[1],[i+1]]) 
    points[2].set_data([[2],[i+2]]) 
    points[3].set_data([[3],[i+3]]) 
    return points 

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

plt.show() 

enter image description here

+0

謝謝響應。這是真的,但我想繪製和更新點,而不是線。您能否告訴我,我必須對代碼進行哪些修改才能繪製點。 –

+0

看看我的答案,用您的要求更新它。如果我的回答有幫助,請不要忘記標記爲正確。 – eyllanesc