You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中计算数据位于趋势线上方的时长?

如何计算数据位于趋势线上方的时长并实现可视化标注

看起来你已经完成了趋势线的拟合,接下来我们只需要几步就能实现你想要的效果——找出数据在趋势线上方的时间段、计算时长,并且在图表上高亮标注出来。我会结合你的代码一步步修改:

完整实现代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 读取并预处理数据
csv = pd.read_csv('data.csv')
data = csv[['time', 'amount']]

# 关键:因为你的时间是倒序的(从10到5),先按时间升序排列,方便后续计算连续区间
data_sorted = data.sort_values('time').reset_index(drop=True)
x_sorted = data_sorted['time']
y_sorted = data_sorted['amount']

# 拟合线性趋势线
z = np.polyfit(x_sorted, y_sorted, 1)
p = np.poly1d(z)
y_pred_sorted = p(x_sorted)

# 1. 判断每个数据点是否位于趋势线上方
above_trend = y_sorted > y_pred_sorted

# 2. 识别连续处于趋势线上方的时间段
intervals = []
current_start = None
for i, (time, is_above) in enumerate(zip(x_sorted, above_trend)):
    # 开始一个新的上方区间
    if is_above and current_start is None:
        current_start = time
    # 结束当前上方区间
    elif not is_above and current_start is not None:
        intervals.append((current_start, x_sorted[i-1]))
        current_start = None
# 处理最后一个未闭合的连续区间
if current_start is not None:
    intervals.append((current_start, x_sorted.iloc[-1]))

# 3. 计算每个连续区间的时长
interval_durations = [(end - start) for start, end in intervals]

# 4. 可视化并标注结果
plt.figure(figsize=(10, 6))
plt.plot(x_sorted, y_sorted, 'bo-', label='原始数据')
plt.plot(x_sorted, y_pred_sorted, 'r--', label='趋势线')

# 高亮趋势线上方的区间,并标注时长
for (start, end), duration in zip(intervals, interval_durations):
    # 用半透明绿色标记区间
    plt.axvspan(start, end, color='green', alpha=0.2)
    # 在区间中间位置标注时长(偏移一点避免和趋势线重叠)
    mid_time = (start + end) / 2
    mid_y = p(mid_time) + 0.3
    plt.text(mid_time, mid_y, f'时长: {duration}', ha='center', fontsize=10)

plt.xlabel('时间')
plt.ylabel('数值')
plt.title('数据与趋势线对比(标注趋势线上方时长)')
plt.legend()
plt.show()

# 输出计算结果
print("趋势线上方的时间段:", intervals)
print("对应时长:", interval_durations)

关键步骤解释

  1. 数据排序:你的原始时间是倒序的,先按时间升序排列能确保我们正确识别连续的时间段,避免计算出错。
  2. 判断是否在趋势线上方:通过对比原始数据的amount和趋势线的预测值y_pred_sorted,得到布尔数组above_trend。
  3. 识别连续区间:遍历排序后的数据,记录每个连续处于趋势线上方的开始和结束时间。
  4. 可视化标注:用axvspan绘制半透明的区间阴影,用text在区间中间标注对应的时长,让结果更直观。

运行这段代码后,你就能得到类似目标图的效果,同时控制台会输出每个趋势线上方区间的具体时间范围和时长。

内容的提问来源于stack exchange,提问作者Maximus39

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:27:42