簡體   English   中英

使用 Matplotlib (Python) 動畫條形圖

[英]Animating a bar graph with Matplotlib (Python)

我最近寫這篇文章是為了抓取日志並顯示其中最常用的單詞 matplotlib.pyplot.bar plot

import re
from datetime import datetime
from collections import Counter

import matplotlib.pyplot as plt
from matplotlib import animation

def read_log(path, index, separator=chr(9)):
    data = []
    my_file = open(path,"r+")
    rows = my_file.readlines()
    for row in rows:
        line = re.sub(r'\r\n|\r|\n','',row, flags=re.M)
        if line != '':
            data.append(line.split(separator)[index])
    my_file.close()
    return Counter(data)

def set_plot(counter_data):
    plt.title('This is a title')
    plt.bar(range(len(counter_data)), list(counter_data.values()), align='center')
    plt.xticks(range(len(counter_data)), list(counter_data.keys()))
    plt.tight_layout()
    plt.show()

counter_data = read_log(r'logfile.txt',2)
print(counter_data)
set_plot(counter_data)

我很想為 plot 制作動畫,但是,我無法理解animation.FuncAnimation()

你能幫我嗎?

我添加了這些行:

fig = plt.Figure()
animation.FuncAnimation(fig, set_plot(counter_data), frames=20)

並刪除plt.show()

所以我可以給 FuncAnimation 一個空圖(圖)和 function。 但它不起作用。 編輯:它也不會打印錯誤。

主要問題是FuncAnimation需要一個返回藝術家對象的可調用對象。 將使用框架參數重復調用可調用對象。

在您的示例中, set_plot()被調用一次。 它的返回值( None )被傳遞給FuncAnimation 相反,您應該有一個方法,例如update_plot() ,它從文件中加載數據,更新條形 plot 並返回條形 plot。 這個 function(function 本身)應該傳遞給FuncAnimation

 animation.FuncAnimation(fig, update_plot, frames=20)

沒有調用它! 請注意update_plot后缺少的括號。 動畫文檔顯示了如何做到這一點的示例。

看來您的數據是 static (您從文件中獲取一次並且它不會改變),所以我不太明白您要制作什么動畫。 但是,您的代碼包含需要修復的錯誤,因此出於演示目的,我將在 animation 的每個步驟中添加每個高度的增量。

第一個錯誤是您將 arguments 傳遞給 function 的方式。 對於 arguments 您必須使用fargs參數,否則在您的版本中,您傳遞的結果是 function 而不是 function 本身。

你必須有一個 function (我的版本中是animate ,你的版本中是set_plot ),它為 animation 的每個步驟更新 plot。 (在您的情況下,您每次只需輸入相同的數據)

function 需要接受至少一個參數( val ),該參數用於我的FuncAnimation ,它將從迭代器獲得的值傳遞給它的frames參數。

最終代碼如下所示

import re
from datetime import datetime
from collections import Counter
import matplotlib.pyplot as plt
from matplotlib import animation
# uncomment if using in jupyter notebook
# %matplotlib nbagg 

def read_log(path, index, separator=chr(9)):
    data = []
    my_file = open(path,"r+")
    rows = my_file.readlines()
    for row in rows:
        line = re.sub(r'\r\n|\r|\n','',row, flags=re.M)
        if line != '':
            data.append(line.split(separator)[index])
    my_file.close()
    return Counter(data)

fig = plt.figure()
ax = fig.add_subplot()
counter_data = read_log(r'tmp.csv',2)
plt.title('This is a title')
bar = ax.bar(range(len(counter_data)), list(counter_data.values()), align='center')
plt.xticks(range(len(counter_data)), list(counter_data.keys()))
plt.tight_layout()
plt.ylim((0, 30))


def animate(val, counter_data):
    data = list(counter_data.values())
    for i in range(len(data)):
        bar[i].set_height(data[i]+val)

animation.FuncAnimation(fig, func=animate, frames=20, fargs=[counter_data], save_count=10)

我們得到以下 animation:

動畫


編輯

對於錯誤,您可以嘗試將 animation 保存為 gif,然后會顯示錯誤

anim = animation.FuncAnimation(fig, func=animate, frames=20, fargs=[counter_data], save_count=10)
anim.save('anim.gif', 'imagemagick')

暫無
暫無

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

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