2017-06-15 49 views
3

我试图绘制我收到的每月数据图。绘制数据时,绘图仅显示x轴上的年份,但不显示月份。我怎样才能让它在x tick标签上显示月份?如何在使用日期范围时使x轴更加细致

import pandas as pd 
import numpy as np 
new_index = pd.date_range(start = "2012-07-01", end = "2017-07-01", freq = "MS") 
columns = ['0'] 
df = pd.DataFrame(index=new_index, columns=columns) 

for index, row in df.iterrows(): 
    row[0] = np.random.randint(0,100) 
    %matplotlib inline 
    df.loc['2015-09-01'] = np.nan 
    df.plot(kind="line",title="Data per month", figsize = (40,10), grid=True, fontsize=20) 

enter image description here

回答

2

您可以使用从matplotlib.tickerFixedFormatter定义自己的格式自定义蜱喜欢这里:

... 
ticklabels = [item.strftime('%b %Y') for item in df.index[::6]] # set ticks format: month name and year for every 6 elements of index 
plt.gca().xaxis.set_ticks(df.index[::6]) # set new ticks for current x axis 
plt.gca().xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels)) # apply new tick format 

... 

enter image description here

或日期两行,如果使用%b\n%Y格式: enter image description here