首页 > 解决方案 > 如何在不计算 Python 中的时间数据列的情况下绘制时间序列

问题描述

我有一个数据框,它只包含在 10 小时内采集的一列数据(3.000.000 个样本)。可以假设采样频率是恒定的。

是否可以创建时间序列线图而不必创建具有某种时间戳/日期时间的另一列?

我知道:

-Y轴应该是样本的值

-X 轴应该是时间。原点等于 0,轴的最后一个标记是 10 小时。

我看到的所有示例都假设有一列带有时间戳,但我想如果我知道周期(0 h - 10 h)并假设数据/样本的频率恒定,则不需要计算它。

标签: pythonmatplotlibtime-series

解决方案


如果数据是均匀分布的,我们可以简单地根据索引绘制并使用 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()

之前的示例输出... 在此处输入图像描述 ...和缩放之后 在此处输入图像描述

这可以适应其他时间范围 - 目前,您不能缩小到零以下的负时间值。


推荐阅读