2016-08-19 67 views
0

我是python編程的新手,並且一直在試圖將數字與日期相加。唯一的問題是,當我單獨繪製它時,似乎會顯示我的日期範圍內的每一個日期。因此x軸是完全難以辨認的。有沒有辦法保留我所有的數據點,但是X軸只顯示月份的日期或類似的東西?僅繪製某個數組中的某些日期

的代碼,用一些樣本數據,是如下:

import datetime as dt 
import matplotlib.dates as mdates 
import matplotlib.pyplot as plt 
dates=['1/08/2015', '2/08/2015', '1/09/2015', '2/09/2015', '3/09/2015','4/09/2015', '5/09/2015', '1/10/2015', '2/11/2015', '3/11/2015', '4/11/2015', '5/11/2015', '1/12/2015', '2/12/2015', '1/01/2016', '2/01/2016', '3/01/2016', '1/02/2016', '2/02/2016', '3/02/2016', '4/02/2016', '1/03/2016', '6/03/2016', '1/04/2016', '2/05/2016', '1/06/2016', '1/07/2016', '2/07/2016', '3/07/2016', '4/07/2016', '5/07/2016', '1/08/2016', '2/08/2016', '3/08/2016'] 
converteddates= [dt.datetime.strptime(d, '%d/%m/%Y').date() for d in dates] 
data=range(len(converteddates)) 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
plt.plot(converteddates,data) 
plt.gcf().autofmt_xdate() 
plt.show() 

回答

0

您應該使用MonthLocator(DayLocator的工作就是把蜱在日常):

plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) 
plt.plot(converteddates,data) 
plt.gcf().autofmt_xdate() 

但更好的方法可能是:

fig, ax = plt.subplots() 
ax.plot_date(converteddates, data) 

如果它仍然不喜歡你的日期,那麼在下面設置滴答和標籤:

ax.set_xticks(converteddates) 
strdates = [d.strftime("%d/%m/%Y") for d in converteddates] 
ax.set_xticklabels(strdates, rotation="45")