2016-08-02 78 views
0

我想將下面的代碼轉換爲循環遍歷x值的動畫,而不僅僅是像當前那樣返回一個x值。如何創建循環播放一系列matpyplot.pyplot imshows的動畫

import numpy as np 
import matplotlib.pyplot as plt 

def sliceplot(file_glob,xslice): 
    """User inputs location of binary data file 
    and single slice of x axis is returned as plot""" 

    data=np.fromfile(file_glob,dtype=np.float32) 
    data=data.reshape((400,400,400)) 
    plt.imshow(data[xslice,:,:]) 
    plt.colorbar() 
    plt.show() 

我曾嘗試下面這個例子,但似乎無法把它翻譯成什麼,我需要:http://matplotlib.org/examples/animation/dynamic_image.html

你可以提供任何幫助將不勝感激。

回答

0

是這樣的,你喜歡做什麼?我下面的例子 - 基於this的例子 - 正在使用腳本中定義的函數generate_image的一些虛擬圖像。根據我對您的問題的理解,您寧願爲每次迭代都加載一個新文件,這可以通過替換generate_image的功能來完成。你可能應該使用一組file_names而不是像我這樣在數組中使用數據矩陣,但爲了透明度,我使用這種方法(但對於大型數據集來說它是非常不夠的!)。

而且我還添加了兩個額外的參數給FuncAnimation -call,1)確保當你出的圖像(與frames=len(images))和2)fargs=[images, ]傳遞圖像陣列到功能停止。您可以閱讀更多here

還要注意的是

#!/usr/bin/env python 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

def generate_image(n): 
    def f(x, y): 
     return np.sin(x) + np.cos(y) 
    imgs = [] 
    x = np.linspace(0, 2 * np.pi, 120) 
    y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) 
    for i in range(n): 
     x += np.pi/15. 
     y += np.pi/20. 
     imgs.append(f(x, y)) 
    return imgs 


images = generate_image(100) 

fig, ax = plt.subplots(1, 1)  
im = ax.imshow(images[0], cmap=plt.get_cmap('coolwarm'), animated=True) 

def updatefig(i, my_arg): 
    im.set_array(my_arg[i]) 
    return im, 

ani = animation.FuncAnimation(fig, updatefig, frames=len(images), fargs=[images, ], interval=50, blit=True) 
plt.show() 

文件名裝載機的一個例子是像

def load_my_file(filename): 
    # load your file! 
    ... 
    return loaded_array 

file_names = ['file1', 'file2', 'file3'] 

def updatefig(i, my_arg): 
    # load file into an array 
    data = load_my_file(my_arg[i]) # <<---- load the file in whatever way you like 
    im.set_array(data) 
    return im, 

ani = animation.FuncAnimation(fig, updatefig, frames=len(file_names), fargs=[file_names, ], interval=50, blit=True) 
plt.show() 

希望它能幫助!