2017-04-15 113 views
1

下面的示例代码中,我想提请整个日期在x轴上[matplotlib]:写在x轴上日期

import datetime 
import matplotlib.pyplot as plt 
import random 
import numpy as np 
from matplotlib.dates import DateFormatter 

years = np.arange(2005, 2016, 1) 
years[1] = 2005 
years[2] = 2005 
months = [ 3, 2, 1, 5, 7, 12, 2, 3, 5, 2, 6] 
dates = [] 
for Y in years: 
    dates = dates + [ datetime.datetime(Y, 6 , 4) ] 


y = np.random.randn(len(dates)) 

fig, ax = plt.subplots() 

ax.plot_date(dates, y, 'r+', ms = 2, mew = 12) 

ax.fmt_xdata = DateFormatter('%y-%m-%d') 
fig.autofmt_xdate() 

plt.show() 

不幸的是,结果是这样的 enter image description here

什么我需要的是所有写在x轴上的日期就像在这张照片

enter image description here

你的建议是什么我改变我的代码?

回答

1

ax.fmt_xdata是日期的格式化程序,通常只用于交互式绘图中的悬停功能。 enter image description here

你想要的这里是于x轴的主要格式设置为DateFormatter

ax.xaxis.set_major_formatter(DateFormatter('%b-%d-%Y')) 

enter image description here