python - 如何在 x 轴上绘制带有日期时间的线性回归

标签 python pandas matplotlib time-series linear-regression

我的 DataFrame 对象看起来像

            amount
date    
2014-01-06  1
2014-01-07  1
2014-01-08  4
2014-01-09  1
2014-01-14  1

我想要一种散点图,x 轴为时间,y 轴为数量,数据中有一条线来引导观察者的视线。如果我使用 pandas plot df.plot(style="o") 它不太正确,因为那条线不在那里。我想要类似示例的东西 here .

最佳答案

注意:这与 Ian Thompson 的回答有很多共同之处,但方法不同,足以将其作为一个单独的答案。我使用问题中提供的 DataFrame 格式并避免更改索引。

Seaborn 和其他库无法像您希望的那样处理日期时间轴。以下是我的解决方法:

首先添加一列日期序数

Seaborn 会比处理日期更好地处理这些。这是用日期和不喜欢日期的库做各种数学运算的便捷技巧。

from datetime import date

df['date_ordinal'] = pd.to_datetime(df['date']).apply(lambda date: date.toordinal())

dataframe with ordinals

在日期轴上绘制序数图

ax = seaborn.regplot(
    data=df,
    x='date_ordinal',
    y='amount',
)
# Tighten up the axes for prettiness
ax.set_xlim(df['date_ordinal'].min() - 1, df['date_ordinal'].max() + 1)
ax.set_ylim(0, df['amount'].max() + 1)

用漂亮、可读的日期替换有序的 X 轴标签

ax.set_xlabel('date')
new_labels = [date.fromordinal(int(item)) for item in ax.get_xticks()]
ax.set_xticklabels(new_labels)

plot with regression line

哒哒哒!

关于python - 如何在 x 轴上绘制带有日期时间的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308729/

相关文章:

python - 在 Pandas 中 reshape 宽到长

python - 以 3D 形式绘制分段函数

python - Pandas Dataframe 的 Csv 缺少列

python - Django 模型 - 分配 id 而不是对象

python - 使用 python 进行数据分析

python - 使用 Pandas 组合数据框中两行的不同部分

matplotlib - 使用 SciPy 树状图,我可以更改线宽吗?

python - 在不使用 xticks 的情况下设置二维等高线图的轴值

Python:如何在不保存文件的情况下处理来自 Web 的 excel 数据

Python 等价于 SQL 中的不等式连接