且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 pandas 和日期时间格式进行绘图

更新时间:2023-02-26 16:37:31

编辑2 .为了使新手了解python,您应该首先导入熊猫以使下面的代码起作用:

EDIT 2 after seeing more people ending up here. To be clear for new people to python, you should first import pandas for the codes bellow to work:

import pandas as pd

编辑1 :(简短快速答案)

如果³您不想删除原始索引(在阅读原始且冗长的答案之后,这很有意义),您可以:

If³ you don't want to drop your original index (this makes sense after reading the original and long answer bellow) you could:

df[['Date','ClosingPrice']].plot('Date', figsize=(15,8))

原始答案和长答案:

首先尝试将索引设置为日期时间"列:

Try setting your index as your Datetime column first:

df.set_index('Date', inplace=True, drop=True)

可以肯定的是,请尝试设置索引dtype(可能不需要像以前一样进行此操作):

Just to be sure, try setting the index dtype (edit: this probably wont be needed as you did it previously):

df.index = pd.to_datetime(df.index)

然后绘制

df.plot()

如果这解决了问题,那是因为当您使用DataFrame对象中的.plot()时,X轴将自动成为DataFrame的索引.

If this solves the issue it's because when you use the .plot() from DataFrame object, the X axis will automatically be the DataFrame's index.

如果²您的DataFrame具有Datetimeindex和另外2列(例如['Currency','pct_change_1']),而您只想绘制其中之一(也许是pct_change_1),则可以:

If² your DataFrame had a Datetimeindex and 2 other columns (say ['Currency','pct_change_1']) and you wanted to plot just one of them (maybe pct_change_1) you could:

# single [ ] transforms the column into series, double [[ ]] into DataFrame
df[['pct_change_1']].plot(figsize=(15,8)) 

figsize=(15,8)处,您要设置图(width, height)的大小.

Where figsize=(15,8) you're setting the size of the plot (width, height).