分享

我可以使用seaborn在x轴上绘制带日期时间的线性回归吗?

 印度阿三17 2019-06-23

我的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上的数量,用数据线来引导观察者的眼睛.如果我使用panadas plot df.plot(style =“o”)那就不太对了,因为线路不在那里.我想要像here这样的例子.

解决方法:

由于Seaborn遇到日期问题,我将创建一个解决方案.
首先,我将Date列作为索引:

# Make dataframe
df = pd.DataFrame({'amount' : [1,
                               1,
                               4,
                               1,
                               1]},
                  index = ['2014-01-06',
                           '2014-01-07',
                           '2014-01-08',
                           '2014-01-09',
                           '2014-01-14'])

其次,将索引转换为pd.DatetimeIndex:

# Make index pd.DatetimeIndex
df.index = pd.DatetimeIndex(df.index)

并用它替换原件:

# Make new index
idx = pd.date_range(df.index.min(), df.index.max())

第三,使用新索引(idx)重新索引:

# Replace original index with idx
df = df.reindex(index = idx)

这将生成一个新的数据框,其中包含您没有数据的日期的NaN值:

df edit

第四,由于Seaborn对日期和回归线不起作用,我将创建一个行计数列,我们可以将其用作x轴:

# Insert row count
df.insert(df.shape[1],
          'row_count',
          df.index.value_counts().sort_index().cumsum())

第五,我们现在应该能够使用’row_count’作为我们的x变量和’amount’作为y变量来绘制回归线:

# Plot regression using Seaborn
fig = sns.regplot(data = df, x = 'row_count', y = 'amount')

第六,如果您希望日期沿x轴而不是row_count,您可以将x-tick标签设置为索引:

# Change x-ticks to dates
labels = [item.get_text() for item in fig.get_xticklabels()]

# Set labels for 1:10 because labels has 11 elements (0 is the left edge, 11 is the right
# edge) but our data only has 9 elements
labels[1:10] = df.index.date

# Set x-tick labels
fig.set_xticklabels(labels)

# Rotate the labels so you can read them
plt.xticks(rotation = 45)

# Change x-axis title
plt.xlabel('date')

plt.show();

plot edit 2

希望这可以帮助!

来源:https://www./content-4-262551.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多