【问题标题】:Update Matplotlib Chart on Dynamically updating DataFrame在动态更新 DataFrame 上更新 Matplotlib 图表
【发布时间】:2022-01-25 16:50:47
【问题描述】:

我有一个空数据框,我一次向它附加一个数据。像这样:

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

tweet_id 是一个整数,sentiment 是一个可以有 3 个值的字符串,即。 “正面”、“负面”、“中性”。现在我有一个附加到数据框的循环:

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

这是有效的,但它正在创建多个图,我需要关闭一个才能查看另一个。每当我运行循环时,我都希望更新相同的情节。我该怎么做?我搜索了它,我得到了使用 numpy 附加或显示折线图的解决方案。

如何使用 pandas groupby() 实现这一目标?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我不确定tweets.groupby('sentiment').count()['tweet_id'].plot.bar() 是否能够在不生成新绘图的情况下更新您的绘图,因为它返回一个matplotlib.axes.Axes 对象(文档here)。

    您可以改为将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()
    

    【讨论】:

    • 由于plt.show()在循环内部,它仍然会生成很多图。
    • @KumarPriyansh 哦,我的错,我把它移到循环之外,希望能解决问题
    • 问题是,情节只会在循环完成后显示,在我的情况下循环是无限的。它永远不会达到plt.show() - 因此根据原始问题,情节更新必须在循环内,并且情节必须仅在每次迭代时更新。
    • @KumarPriyansh 我明白了……在这种情况下,使用 matplotlib 动画 API 可能会更成功
    • 能否按照动画 API 更新您的代码?
    猜你喜欢
    • 2020-12-28
    • 2012-06-12
    • 1970-01-01
    • 2021-11-10
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多