2013-01-02 182 views
8

我想基於在matplotlib 1.1.0動畫與輪廓matplotlib

動畫輪廓: http://www.mail-archive.com/[email protected]/msg17614.htmlhttp://matplotlib.1069221.n5.nabble.com/Matplotlib-1-1-0-animation-vs-contour-plots-td18703.htmlhttp://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data

from numpy import linspace,exp,vstack 
from scipy.interpolate import griddata 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
from numpy.random import uniform, seed 

def main(): 
    seed(1234) 
    x = uniform(-2,2,100) 
    y = uniform(-2,2,100) 
    data = vstack((x*exp(-x**2-y**2),0.5*x*exp(-x**2-y**2),0.2*x*exp(-x**2-y**2))) 
    xi = linspace(min(x), max(x)) 
    yi = linspace(min(y), max(y)) 
    zi = [] 
    numframes = data.shape[0] 
    for ii in range(numframes): 
     zi.append(griddata((x, y), data[ii], (xi[None,:], yi[:,None]), method='cubic')) 

    fig = plt.figure() 
    im = plt.contour(xi, yi, zi[0], 15, linewidths=0.5, colors='k') 
    ani = animation.FuncAnimation(fig, update_contour_plot, frames=xrange(numframes), fargs=(zi, im, fig, xi, yi), interval=100) 
    plt.colorbar() 
    plt.show() 

def update_contour_plot(i, data, im, fig, xi, yi): 
    for coll in im.collections: 
     try: 
      plt.gca().collections.remove(coll) 
     except ValueError: #Everything is not removed for some reason!                      
      pass 
    im = plt.contour(xi, yi, data[i], 15, linewidths=0.5, colors='k') 
    plt.title(str(i)) 
    return im, 

main() 

1)這是做到這一點的最好辦法?另有提及。

2)在最終輸出中,前一幀的輪廓線仍然可見。我如何刪除它們?請參閱ValueError除外:

+0

'ValueError'是否攜帶任何消息? – tacaswell

+0

沒有嘗試:除了:讀出是 plt.gca()collections.remove(科爾) ValueError異常:list.remove(X):在列表 – chaitu

+0

+1很好的例子代碼 – tacaswell

回答

1

您有一個範圍問題,您在更新程序中創建的新im未被傳回,因此,第二次通過循環嘗試再次刪除第一層線,正確地抱怨它不能,因爲你已經刪除它們。

調整你的代碼位:

def main(): 
    seed(1234) 
    x = uniform(-2,2,100) 
    y = uniform(-2,2,100) 
    data = vstack((x*exp(-x**2-y**2),0.5*x*exp(-x**2-y**2),0.2*x*exp(-x**2-y**2))) 
    xi = linspace(min(x), max(x)) 
    yi = linspace(min(y), max(y)) 
    zi = [] 
    numframes = data.shape[0] 
    for ii in range(numframes): 
     zi.append(griddata((x, y), data[ii], (xi[None,:], yi[:,None]), method='cubic')) 

    fig = plt.figure() 
    im = plt.contour(xi, yi, zi[0], 15, linewidths=0.5, colors='k') 
    ax = fig.gca() 
    ani = animation.FuncAnimation(fig, update_contour_plot, frames=xrange(numframes), fargs=(zi, ax, fig, xi, yi), interval=100) 
    plt.colorbar(im) 
    plt.show() 
    return ani 


def update_contour_plot(i, data, ax, fig, xi, yi): 
    ax.cla() 
    im = ax.contour(xi, yi, data[i], 15, linewidths=0.5, colors='k') 
    plt.title(str(i)) 
    return im, 

另一種選擇是讓im一個可變某種(如包裝在一個字典),這樣的更改會從一幀傳播到幀。

+0

ValueError異常X不是:名單.remove(x):x不在列表中 – chaitu

+0

@chaitu請參閱編輯。 – tacaswell

+0

現在運作。謝謝! – chaitu