繁体   English   中英

在x轴上绘制格式为月年的熊猫数据框索引

[英]Plot pandas dataframe index formatted as Month-Year on x axis

例如,我有一个数据框,希望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()

第二个索引应该只是日期而不是时间,但是它会错误地绘制如下图: 错误的图

这应该可以解决问题。 当然,有“更漂亮”的方法,但是我已经尝试过这样做,以便您可以使数据和原始数据帧与问题中的原始数据帧尽可能接近。

在注释后编辑 :那么如何处理,只需创建一个新列,并以您想要的任何形状格式化日期即可。 然后使用set_xticklabels()传递该列以设置所需的刻度。 另外,您可能希望删除默认的plt.xlabel(否则,在xticks下方将有索引名称)。

import datetime as dt
import pandas as pd
import time
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# the first part of your code is the same
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')

# first let's give a name to the indexes
df.index.names = ['ivog', 'timestamp']

# then create a new column with a datetime object
# (formatted to microseconds as your data seems to be)
df['date'] = pd.to_datetime(df.index.levels[1], 
unit='ms')

# now let's change the date to the format you want
df['date'] = df['date'].apply(lambda x: x.strftime("%Y %B"))


print(df)

# plot the data just like you were doing
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)

# Now the x-axis label should be what you wished for
ax.set_xticklabels(df['date'])
plt.xlabel('Your x axis label') 
plt.ylabel('Your y axis label')
plt.title('My Awseome Plot')
plt.xticks(rotation=45)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM