簡體   English   中英

如何 plot 直方圖或條形圖 animation 與 matplotlib ArtistAnimation?

[英]How to plot an histogram or bar animation with matplotlib ArtistAnimation?

我正在嘗試創建一個一個堆疊樣本的直方圖 animation。 我認為下面的代碼可以工作,但事實並非如此。

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 顯示 animation。 不知道有什么區別。

謝謝閱讀。

plt.hist不返回藝術家,而是返回帶有分箱結果和藝術家的元組(參見此處)。

這也在 Matplotlib 郵件列表中的此線程中進行了討論:

ArtistAnimation 期望得到一個列表(或元組)列表,其中內部集合包含應為給定幀渲染的所有藝術家。 在 bar 的情況下,它返回一個 BarCollection object(我剛剛學過),是元組的子類。 這解釋了當直接附加到給 ArtistAnimation 的列表時,它為什么(單獨)起作用; BarCollection 充當 ArtistAnimation 期望的藝術家集合。 在第二個例子中,ArtistAnimation 被賦予一個 list([BarCollection, Image]); 因為 BarCollection 實際上不是藝術家,所以它會導致問題。

那里提到的問題使用不同的 plot 類型:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM