【问题标题】:How to Find Trend Line and Calculate Slope of Trend Line with X-Axis如何找到趋势线并用 X 轴计算趋势线的斜率
【发布时间】:2020-01-16 01:23:03
【问题描述】:

我有一个如下所示的 Pandas 数据框:

 UNDERLAY   TIME
 27,395     09:15:18
 27,466     09:17:19
 27,391     09:19:06
 27,409     09:21:19
 27,439     09:23:21
 27,468     09:25:58
 27,497     09:27:19
 27,502     09:29:54
 27,542     09:31:19
 27,522     09:33:33
 27,520     09:35:09
 ...

我想绘制这些UNDERLAY 值的趋势线并计算 X 轴的斜率。

从以下链接获得了一些帮助,但无法找到坡度: How can I draw scatter trend line on matplot? Python-Pandas

【问题讨论】:

标签: python python-3.x pandas matplotlib


【解决方案1】:

seanborn.regplot是最快的制作情节的方法:

import seaborn as sns

df_plot = pd.DataFrame()
# seconds since midnight of each TIME value
df_plot['SECONDS'] = (pd.to_datetime(df['TIME']) - pd.Timestamp.now().normalize()).dt.total_seconds()
df_plot['UNDERLAY'] = pd.to_numeric(df['UNDERLAY'].str.replace(',', ''))

ax = sns.regplot(data=df_plot, x='SECONDS', y='UNDERLAY')
ax.set(
    xticklabels=pd.to_datetime(ax.get_xticks(), unit='s').strftime('%H:%M'),
    xlabel='Time',
    ylabel='Underlay'
)
plt.show()

输出:

要得到回归函数,使用numpy:

import numpy as np
f = np.polyfit(df_plot['SECONDS'], df_plot['UNDERLAY'], deg=1)

# Slope
f[0]

# Make a prediction at 21:00
# Time is expressed as seconds since midnight
np.polyval(f, 21*3600)

【讨论】:

  • 你忘了 import matplotlib.pyplot as plt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 2011-02-15
  • 2021-07-25
  • 1970-01-01
相关资源
最近更新 更多