python - 如何在不计算 Python 中的时间数据列的情况下绘制时间序列
问题描述
我有一个数据框,它只包含在 10 小时内采集的一列数据(3.000.000 个样本)。可以假设采样频率是恒定的。
是否可以创建时间序列线图而不必创建具有某种时间戳/日期时间的另一列?
我知道:
-Y轴应该是样本的值
-X 轴应该是时间。原点等于 0,轴的最后一个标记是 10 小时。
我看到的所有示例都假设有一列带有时间戳,但我想如果我知道周期(0 h - 10 h)并假设数据/样本的频率恒定,则不需要计算它。
解决方案
如果数据是均匀分布的,我们可以简单地根据索引绘制并使用 matplotlib 提供的FuncFormatter 类更改刻度的标签,从而避免为确定每个数据点的时间而进行大量计算:
from matplotlib import pyplot as plt
from matplotlib.ticker import LinearLocator, FuncFormatter
from datetime import datetime as dt
#fake data generation
import numpy as np
np.random.seed(123)
n=3000
arr = np.random.random(n)
last_index = len(arr)-1
#time in h
total_time = 10
#plot the array against the index
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(arr)
ax.set_xlim(0, last_index)
ax.tick_params(axis="x", labelrotation=90)
#formatter function to convert the index value into a time string
def ind2date(x, pos):
s = dt.fromtimestamp(total_time * 3600 * x / last_index)
return s.strftime("%H:%M:%S.%f")
#generates 5 evenly distributed ticks, even if we change the view by zooming in
ax.xaxis.set_major_locator(LinearLocator(5))
ax.xaxis.set_major_formatter(FuncFormatter(ind2date))
plt.tight_layout()
plt.show()
这可以适应其他时间范围 - 目前,您不能缩小到零以下的负时间值。
推荐阅读
- reactjs - 尝试使用 google 按钮添加登录时出错“RN GoogleSignin 本机模块未正确链接...”-本机反应
- javascript - 如何在 Cinnamon Applet 中显示多个对象
- wordpress - 非 www 到 www 不适用于使用 safari 的 EC2 实例中的 wordpress
- python - 如何将鼠标事件传播到 QGraphicsItemGroup 中的 QGraphicsItem?
- android - 在 android studio 中使用终端进行 github 项目
- sql - 用一条记录截断 MS SQL Server Express 表需要很长时间
- argparse - 这个 python3 脚本有什么问题?
- c# - 如何检查任务是否正在运行,如果没有运行则重新启动
- r - 如何编写R代码进行矩阵变换
- python-3.x - Python:掷骰子 12 次,计算每个数字出现两次的概率