我有一个数据帧,我希望x轴显示为例如APR-2018 . ax.format_xdata行不起作用 .
import datetime as dt
import pandas as pd
import time
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
data = {("IVOG",1493510400000):{"Adj_Close":119.2136,"MA(3)":119.2136,"EWMA(3)":119.2136},
("IVOG",1496188800000):{"Adj_Close":120.8236,"MA(3)":120.0186,"EWMA(3)":120.0454},
("IVOG",1498780800000):{"Adj_Close":120.2736,"MA(3)":120.1036,"EWMA(3)":120.1266},
("IVOG",1501459200000):{"Adj_Close":121.7836,"MA(3)":120.5236,"EWMA(3)":120.5832},
("IVOG",1504137600000):{"Adj_Close":120.3536,"MA(3)":120.4896,"EWMA(3)":120.5309},
("IVOG",1506729600000):{"Adj_Close":124.3336,"MA(3)":121.1303,"EWMA(3)":121.2749}}
df=pd.DataFrame.from_dict(data, orient = 'index')
print(df)
ax = plt.gca() # get current axis
df.plot(kind='line',y='Adj_Close', ax=ax)
df.plot(kind='line',y='MA(3)',ax=ax)
df.plot(kind='line',y='EWMA(3)', color='green', ax=ax)
print(df.index[0][1])
ax.format_xdata = mdates.DateFormatter('%b-%Y') # Trying to get APR-2018
plt.xlabel(df.index[0][0]) # Trying to Get the Ticker
_=plt.grid()
_=plt.xticks(rotation=90)
plt.show()
第二个索引应该只是日期而不是时间,但它错误地绘制如下:Incorrect Plot
1 回答
这应该可以解决问题 . 当然,有更“漂亮”的方式,但我试图让它保持您的数据和原始数据框架与您问题中的原始数据框架保持一致 .
Edited after comments :那么怎么样,只需创建一个新列,其中包含您想要的任何形状格式的日期 . 然后使用set_xticklabels()传递该列以根据需要设置刻度 . 您也可以删除默认的plt.xlabel(否则您的xticks下面会有索引的名称) .