python-3.x - 熊猫每分钟绘制价值总和
问题描述
我有一个不断增长的文本文件,其中包含如下数据。它会实时更新,并且数量不断增加。
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)
解决方案
您可以按时间分组,然后对计数求和,将您的函数替换为:
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()
推荐阅读
- csv - 在 CSV DataTables Laravel 8 中导出时的自定义列名称
- image - 颤振删除图像滑块中的左侧空间
- matrix-multiplication - 有效地乘以压缩自伴随矩阵
- stata - AME-dy/dx 之后的 Suest 不为 suest 保存
- python-3.x - 几次干净运行后看到 UnboundLocalError
- visual-studio - 如果可以的话,我可以在 Visual Studio 中使用 matlab 工具箱代码(k-wave)吗?我该如何实现?
- typescript - 从字符串日期中删除时间数据
- celery - 间歇性“无结果后端”异常
- neo4j - 使neo4j列表中存在的元素之间的所有关系
- html - Github 页面给了我 404 而不是链接到不同的页面