簡體   English   中英

更新Matplotlib圖表動態更新DataFrame

[英]Update Matplotlib Chart on Dynamically updating DataFrame

我有一個空的 dataframe ,我一次向它附加一個數據。 像這樣:

# Initialize an empty dataframe to store the tweet id and sentiment
tweets = pd.DataFrame(columns=['tweet_id', 'sentiment'])

tweet_id是一個 integer, sentiment是一個可以有 3 個值的字符串,即。 “正面”、“負面”、“中性”。 現在我有一個附加到 dataframe 的循環:

for i in range(len(whatever_I_want)):
    tweet = get_new_tweet()
    tweets = tweets.append({'tweet_id': tweet['id'], 'sentiment': tweet['sentiment']}, ignore_index=True)
    # Update the plot with the new dataframe
    tweets.groupby('sentiment').count()['tweet_id'].plot.bar()
    plt.show()

這是有效的,但它正在創建多個圖,我需要關閉一個才能查看另一個。 我希望在運行循環時更新相同的 plot 。 我該怎么做? 我搜索了它,我得到了使用 numpy 到 append 或顯示折線圖的解決方案。

如何通過使用 pandas groupby()來實現這一點?

I am not sure that tweets.groupby('sentiment').count()['tweet_id'].plot.bar() will be able to update your plot without generating a new one because it returns a matplotlib.axes.Axes object ( 此處的文檔)。

您可以改為將tweets.groupby('sentiment').count()['tweet_id'])indexvalues傳遞給plt.bar

 for i in range(len(whatever_I_want)):
    tweet = get_new_tweet()
    tweets = tweets.append({'tweet_id': tweet['id'], 'sentiment': tweet['sentiment']}, ignore_index=True)
    # Update the plot with the new dataframe
    grouped_tweets = tweets.groupby('sentiment').count()['tweet_id']
    plt.bar(x=grouped_tweets.index, height=grouped_tweets.values)
    plt.show()

暫無
暫無

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

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