2016-11-17 116 views
0

我想生成一个图形图表,我想将日期显示为“01/03/1991”格式,但使用我的代码获取日期作为“1991年1月3日”。 下面是我用来生成图形的代码。任何人都可以帮助我解决这个问题。以m/d/Y格式在x轴上绘制日期

import numpy as np 
import matplotlib.pyplot as plt 
import datetime as dt 
import matplotlib.dates as mdates 

dates = ['01/02/1991','01/03/1991','01/04/1991', '01/05/1991','01/06/1991','01/07/1991'] 

a = [0, 2.0, 3.0, 4.0, 5.0, 10.0] 
r = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates] 
s = [1.0, 4.0, 9.0, 16.0, 25.0, 40.0] 

fig, ax1 = plt.subplots() 

ax2 = ax1.twinx() 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
lns1 = ax1.plot(r, a, marker='o', label='No. of trip', linewidth=4) 
lns2 = ax2.plot(r, s, marker='o', linestyle='--', color='r', label='No. of customer', linewidth=4) 
plt.gcf().autofmt_xdate() 

ax1.set_xlabel('x') 
ax1.set_ylabel('y1', color='b') 
ax2.set_ylabel('y2', color='r') 

# added these three lines 
lns = lns1+lns2 
labs = [l.get_label() for l in lns] 
ax2.legend(lns, labs, loc=0) 
plt.show() 

回答

1

将格式器应用于错误的对象。你应该把它应用到

ax1 

像这样

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) 
+0

是我没有像以前,但它给了我错误。现在我已修复它。非常感谢你 – nas