亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

matplotlib:條形圖動畫只能工作一次

matplotlib:條形圖動畫只能工作一次

慕姐8265434 2023-04-25 15:40:07
我已經使用FuncAnimation的方法實現了一個動畫matplotlib.animation。代碼沒有錯誤,但我不知道問題到底出在哪里!代碼:def visualization(self):    fig = plt.figure()        def animation_frame(i):        print(i)        trimmed_dist = self.get_distributions(i, self.window_size + i)        # create labels                     label_no = len(trimmed_dist)        labels = []        for index in range(label_no):            from_ = index * self.bucket_length            to_ = (index + 1) * self.bucket_length            label = '{:.2f} - {:.2f}'.format(from_, to_)            labels.append(label)                #create bar chart        colors = plt.cm.Dark2(range(label_no))        plt.xticks(rotation=90)        plt.bar(x=labels, height=trimmed_dist, color=colors)            frames_no = len(self.percentages) - self.window_size    print('frames_no:', frames_no)    animation = FuncAnimation(fig, animation_frame, frames=frames_no, interval=1000)    return animation輸出:PS 1:值為frame_no877。PS 2:我認為問題在于可視化方法中的返回。所以我已經更改了代碼,但它仍然無法正常工作。
查看完整描述

1 回答

?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

我相信您正在 Jupyter 筆記本中運行您的代碼。%matplotlib notebook在這種情況下,您應該在代碼的開頭添加。
中找到的代碼,以查看它是否適合您。


編輯

我在筆記本中實現了你的部分代碼。由于我不知道self.percentages、self.window_size和是什么self.get_distributions以及self.bucket_length它們有哪些值,為了簡單起見,我設置了labels = ['a', 'b', 'c']trimmed_dist = [3*i, 2*i, i**2],以便運行一個簡單的動畫。
這是我的代碼:

%matplotlib notebook

from matplotlib.animation import FuncAnimation

import matplotlib.pyplot as plt


def animation_frame(i):

? ? plt.gca().cla()

? ??

? ? labels = ['a', 'b', 'c']

? ? trimmed_dist = [3*i, 2*i, i**2]

? ? label_no = len(trimmed_dist)

? ??

? ? colors = plt.cm.Dark2(range(label_no))

? ? plt.xticks(rotation=90)

? ? plt.bar(x=labels, height=trimmed_dist, color=colors)

? ? plt.title(f'i = {i}') # this replaces print(i)

? ? plt.ylim([0, 100])? ? # only for clarity purpose


fig = plt.figure()

frames_no = 877

print('frames_no:', frames_no)

animation = FuncAnimation(fig, animation_frame, frames=frames_no, interval=1000)

這就是結果。

我添加plt.gca().cla()是為了在每次迭代時擦除前一幀。
print(i)聲明對我也不起作用,所以我將其替換plt.title(f'i = {i}')為 order 以便寫i在標題中。相反,print('frames_no:', frames_no)工作正常。

如您所見,我的動畫運行了,所以請嘗試實現我對您的代碼所做的更改。
如果動畫仍然不運行,請嘗試檢查self.percentages、self.window_sizeself.get_distributionsself.bucket_length值和類型,以確保正確計算labels和。trimmed_dist


查看完整回答
反對 回復 2023-04-25
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號