首页 > 解决方案 > 熊猫每分钟绘制价值总和

问题描述

我有一个不断增长的文本文件,其中包含如下数据。它会实时更新,并且数量不断增加。

count,time
1,2020-04-06 21:57:00
2,2020-04-06 21:57:00
3,2020-04-06 21:57:00
4,2020-04-06 21:57:00
5,2020-04-06 21:57:00
6,2020-04-06 21:57:00
7,2020-04-06 21:58:00
8,2020-04-06 21:58:00
9,2020-04-06 21:59:00
10,2020-04-06 21:59:00
11,2020-04-06 21:59:00
12,2020-04-06 22:00:00
13,2020-04-06 22:00:00
14,2020-04-06 22:01:00
15,2020-04-06 22:01:00
16,2020-04-06 22:02:00

我想现场绘制每分钟的计数总和,如下所示。

2020-04-06 21:57:00 21 2020-04-06 21:58:00 15 2020-04-06 21:59:00 30 2020-04-06 22:00:00 25 2020-04-06 22:01:00 29 2020-04-06 22:02:00 16

以下代码是我尝试过的。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count()


def animate(i):
    data = pd.read_csv('output.txt')
    data['time'] = pd.to_datetime(data['time'])
    data = data.set_index(['time'])
    x = data.index
    y1 = data.groupby(pd.TimeGrouper('1Min')).sum()

    plt.cla()

    plt.plot(x, y1, label='count')
    plt.xticks(rotation=90)

    plt.legend(loc='upper left')
    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()

但是,此代码给出以下错误。

ValueError: x and y must have same first dimension, but have shapes (16,) and (6, 1)

标签: python-3.xpandasmatplotlibplotreal-time

解决方案


您可以按时间分组,然后对计数求和,将您的函数替换为:

def animate(i):
    data = pd.read_csv('output.txt')
    data['time'] = pd.to_datetime(data['time'])
    data = .groupby('time')['count'].sum()
    x = data.index
    y1 = data['count']
    plt.cla()

    plt.plot(x, y1, label='count')
    plt.xticks(rotation=90)

    plt.legend(loc='upper left')
    plt.tight_layout()

推荐阅读