我可以在Seaborn的x轴上绘制日期时间的线性回归吗? [英] Can I plot a linear regression with datetimes on the x-axis with seaborn?
问题描述
我的DataFrame对象看起来像
My DataFrame object looks like
amount
date
2014-01-06 1
2014-01-07 1
2014-01-08 4
2014-01-09 1
2014-01-14 1
我想要一种散布图,其中沿x轴的时间为时间,沿y的量为时间,并通过一条数据线来引导观察者的眼睛.如果我使用panadas图df.plot(style="o")
,则不太正确,因为该行不存在.我想在示例此处.
I would like a sort of scatter plot with time along the x-axis, and amount on the y, with a line through the data to guide the viewer's eye. If I use the panadas plot df.plot(style="o")
it's not quite right, because the line is not there. I would like something like the examples here.
推荐答案
注意:这与Ian Thompson的答案有很多共同点,但是方法不同,足以将其作为一个单独的答案.我使用问题中提供的DataFrame格式,并避免更改索引.
Seaborn和其他库对日期时间轴的处理不尽如人意.这是我的解决方法:
Seaborn and other libraries don't deal as well with datetime axes as you might like them to. Here's how I'd work around it:
与日期相比,Seaborn会更好地处理这些问题.对于使用日期和不喜欢日期的库进行各种数学运算的人来说,这是一个方便的技巧.
Seaborn will deal better with these than with dates. This is a handy trick for doing all kind of mathy things with dates and libraries that don't love dates.
df['date_ordinal'] = pd.to_datetime(df['date']).apply(lambda date: date.toordinal())
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)
ta-daa!
这篇关于我可以在Seaborn的x轴上绘制日期时间的线性回归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!