如何创建循环播放一系列matpyplot.pyplot imshows的动画
问题描述:
我想将下面的代码转换为循环遍历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
你可以提供任何帮助将不胜感激。
答
是这样的,你喜欢做什么?我下面的例子 - 基于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()
希望它能帮助!