2014-01-12 36 views
3

我正在嘗試爲演示文稿製作動畫數據。我正在嘗試使用python的動畫包來這樣做。我所試圖做的大致歸結爲第一個例子中http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/使用不同顏色的線條生成動畫

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

# First set up the figure, the axis, and the plot element we want to animate 
fig = plt.figure() 
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 
line, = ax.plot([], [], lw=2) 

# initialization function: plot the background of each frame 
def init(): 
    line.set_data([], []) 
    return line, 

# animation function. This is called sequentially 
def animate(i): 
    x = np.linspace(0, 2, 1000) 
    y = np.sin(2 * np.pi * (x - 0.01 * i)) 
    line.set_data(x, y) 
    return line, 

# call the animator. blit=True means only re-draw the parts that have changed. 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
          frames=200, interval=20, blit=True) 

我是新來的蟒蛇,所以我用理解發生了什麼掙扎。對我來說,似乎init()和animate(i)都不修改它們返回的內容。而且,他們正在修改的對象,行(而不是行),以前沒有聲明過。

無論哪種方式,我想要做的是讓數據,在這種情況下,正弦波,分段着色。藍色在0和1之間,紅色在1和1.5之間,並且在1.5和2之間再次變成藍色。我嘗試了很多東西,但是無法讓它工作。我試着讓這些函數返回整個圖形,不僅是線條,而且希望它們能夠刷新預覽圖形並繪製我繪製的複合線條,但無濟於事。

在這個框架中,我怎樣才能讓一行由不同顏色的行組成的行生成動畫?

回答

2

要繪製其屬性隨其更改的線條,請使用LineCollection。示例herehere。使用LineCollection製作動畫,請參見this示例。

要回答上述代碼在animate()中的工作方式,請使用line.set_data(x, y)重置行x,y屬性。該函數然後返回Matplotlib設置(line,) matplotlib必須在每幀更新的藝術家。

這就是我認爲你正在尋找(啓用blit=true只有當您的平臺支持在最後調用):

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
from matplotlib.collections import LineCollection 
from matplotlib.colors import ListedColormap, BoundaryNorm 

# First set up the figure, the axis, and the plot element we want to animate 
fig = plt.figure() 
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 

cmap = ListedColormap(['b', 'r', 'b']) 
norm = BoundaryNorm([0, 1, 1.5, 2], cmap.N) 

line = LineCollection([], cmap=cmap, norm=norm,lw=2) 
line.set_array(np.linspace(0, 2, 1000)) 
ax.add_collection(line) 

# initialization function: plot the background of each frame 
def init(): 
    line.set_segments([]) 
    return line, 

# animation function. This is called sequentially 
def animate(i): 
    x = np.linspace(0, 2, 1000) 
    y = np.sin(2 * np.pi * (x - 0.01 * i)) 
    points = np.array([x, y]).T.reshape(-1, 1, 2) 
    segments = np.concatenate([points[:-1], points[1:]], axis=1) 
    line.set_segments(segments) 
    return line, 

# call the animator. blit=True means only re-draw the parts that have changed. 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
          frames=200, interval=20) 

enter image description here

+0

非常感謝。我不知道LineCollection。 – Mathusalem

+0

所以我明白這條線是屬於情節的東西,它現在是一個段的集合。但是如何在動畫的定義中修改它?我希望能夠在每次迭代中更新BoundaryNorm和ListedColormap,但是我不能在animate的定義中聲明line = ...。有沒有辦法用它的參數來更新線條本身,而不僅僅是它裏面的內容?是否如果我想要這樣做,我實際上必須更新整個數字,而不是隻更新一行? – Mathusalem

+0

使用'line.set_cmap'和'line.set_norm'。而且你不必更新整個數字。 – gg349