Matplotlib:如何使用大型数据集对pcolormesh进行动画处理



我正在使用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 值的示例。这是修改后的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 网格。

感谢您的帮助!抱歉,如果我没有使用正确的标签。

我可能误解了这里的问题,但在这里使用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()

最新更新