Matplotlib:如何使用大型数据集为pcolormesh设置动画

问题描述 投票:1回答:1

我正在使用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网格。

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

python-2.7 animation matplotlib large-data
1个回答
0
投票

我可能会误解这里的问题,但在这里使用FuncAnimation似乎更合适。

With blitting

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()

Without blitting

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()
© www.soinside.com 2019 - 2024. All rights reserved.