我的DataFrame對(duì)象看起來像
amount
date
2014-01-06 1
2014-01-07 1
2014-01-08 4
2014-01-09 1
2014-01-14 1
我想要一種沿著x軸的時(shí)間散點(diǎn)圖,以及y上的數(shù)量,用數(shù)據(jù)線來引導(dǎo)觀察者的眼睛.如果我使用panadas plot df.plot(style =“o”)那就不太對(duì)了,因?yàn)榫€路不在那里.我想要像here這樣的例子. 解決方法: 由于Seaborn遇到日期問題,我將創(chuàng)建一個(gè)解決方案. 首先,我將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'])
其次,將索引轉(zhuǎn)換為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)
這將生成一個(gè)新的數(shù)據(jù)框,其中包含您沒有數(shù)據(jù)的日期的NaN值:

第四,由于Seaborn對(duì)日期和回歸線不起作用,我將創(chuàng)建一個(gè)行計(jì)數(shù)列,我們可以將其用作x軸:
# Insert row count
df.insert(df.shape[1],
'row_count',
df.index.value_counts().sort_index().cumsum())
第五,我們現(xiàn)在應(yīng)該能夠使用’row_count’作為我們的x變量和’amount’作為y變量來繪制回歸線:
# Plot regression using Seaborn
fig = sns.regplot(data = df, x = 'row_count', y = 'amount')
第六,如果您希望日期沿x軸而不是row_count,您可以將x-tick標(biāo)簽設(shè)置為索引:
# 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();

希望這可以幫助! 來源:https://www./content-4-262551.html
|