如何用matplotlib ArtistAnimation绘制直方图或条形动画?

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

我想创建直方图动画,把样本一个个堆叠起来,我以为下面的代码可以用,但是不行。

import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

ims = []
fig = plt.figure()
x =[1,2,3,3,4,5,5,5,5,6,7,8,9,9,9,9,9,10]

for i in range(len(x)):
    img = plt.hist(x[:i])
    ims.append(img)

ani = ArtistAnimation(fig, ims, interval=100)
plt.show()

把plt.hist改成plt.plot.plot.plot.显示动画。不知道有什么区别。

谢谢你的阅读。

python matplotlib
1个回答
0
投票

plt.hist 并没有返回一个艺术家,而是返回了一个包含分选结果和艺术家的元组(见 此处).

这一点也在 这条 在Matplotlib邮件列表中。

ArtistAnimation期望被赋予一个列表(或元组),其中内部集合包含了所有应该为给定帧渲染的艺术家。在bar的情况下,它返回一个BarCollection对象(我刚刚知道),是tuple的一个子类。 这就解释了为什么当直接附加到给ArtistAnimation的列表中时,它可以工作(自己);BarCollection作为ArtistAnimation所期望的艺术家的集合。在第二个例子中,ArtistAnimation被赋予了一个列表([BarCollection,Image]);因为BarCollection实际上不是一个Artist,所以导致了这个问题。

那里提到的问题使用的是不同的情节类型。

im1 = ax1.imshow(f(xm, ym), aspect='equal', animated=True)
im2 = ax2.bar(xx, a, width=0.9*(b[1]-b[0]), color='C1')

在这种情况下,解决方案是

ims.append([im1] + list(im2))

在你的情况下,使之工作的方法是看一看 plt.hist 并找出艺人被退回的地方,并将其放入正确的列表格式中。

这样就可以了。

import matplotlib.animation as animation

fig = plt.figure()

# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []

for i in range(60):

    # hist returns a tuple with two binning results and then the artist (patches)
    n, bins, patches = plt.hist((np.random.rand(10),))

    # since patches is already a list we can just append it
    ims.append(patches)

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
    repeat_delay=1000,)

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.