我正在使用matplotlib.pyplot
来动画一些数组数据。数据采用强度图的形式,因此我有一个x和y位置的网格,以及与这些位置相关的值。
难点在于我不能简单地更新强度数据,因为x和y位置也会发生变化。
例如,我可以得到类似这样的工作,但它需要首先覆盖整个范围的过度确定的x和y网格:
cax = ax.pcolormesh(x, y, G[:-1, :-1, 0],
vmin=-1, vmax=1, cmap='Blues')
fig.colorbar(cax)
def animate(i):
cax.set_array(G[:-1, :-1, i].flatten())
这样可行,但我最终得到一个相当大的强度数组,主要用零填充。
我找到了一个允许更改x和y值的示例here。这是一个修改过的MWE:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig2 = plt.figure()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
x = np.arange(-9+add, 10+add)
y = np.arange(-9+add, 10+add)
x, y = np.meshgrid(x, y)
ims.append((plt.pcolormesh(x, y, base + add, norm=plt.Normalize(0, 30)),))
im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
plt.show()
这里的问题是双重的。首先,我有大约3000帧,因此列表ims
变得无法管理。其次,如何在帧之间清除数据而不是一次显示每一帧?也许有一个更好的方法呢?
奖励:使用滑块可以替代动画。我以前在这些类型的数据上使用了Slider
,但只是通过初始化一个巨大的x和y网格。
感谢您的帮助!如果我没有使用正确的标签,请道歉。
答案 0 :(得分:0)
我可能在这里误解了这个问题,但在这里使用FuncAnimation
似乎更合适。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
def animate(i):
x = np.arange(-9+i, 10+i)
y = np.arange(-9+i, 10+i)
x, y = np.meshgrid(x, y)
pc = ax.pcolormesh(x, y, base + i, norm=plt.Normalize(0, 30))
return pc,
ax.axis([-9,30,-9,30])
im_ani = animation.FuncAnimation(fig, animate, frames=30, interval=50,
repeat_delay=3000, blit=True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
store=[]
def animate(i):
x = np.arange(-9+i, 10+i)
y = np.arange(-9+i, 10+i)
x, y = np.meshgrid(x, y)
if store:
store[0].remove()
del store[0]
pc = ax.pcolormesh(x, y, base + i, norm=plt.Normalize(0, 30))
store.append(pc)
ax.axis([-9,30,-9,30])
im_ani = animation.FuncAnimation(fig, animate, frames=30, interval=50,
repeat_delay=3000)
plt.show()