使用matplotlib在x轴上设置最小/最大年份

时间:2012-02-29 15:13:14

标签: python matplotlib

我在特定地点绘制了超过16年的碳通量的时间序列。我希望x轴有年(1992-2007)而不是年数(1-16)。当我将x轴设置为最小值为1992且最大值为2007时,图形不会出现在图表上,但是当我没有设置最小/最大年份时,它会出现。我不确定我做错了什么。我在一年内绘制了另一个时间序列,并且能够使用MonthLocator标记x轴与月份,但是我没有使用YearLocator。这是我写的代码:

fig=pyplot.figure()
ax=fig.gca()
ax.plot_date(days,nee,'r-',label='model daily nee')
ax.plot_date(days,nee_obs,'b-',label='obs daily nee')

# locate the ticks
ax.xaxis.set_major_locator(YearLocator())

# format the ticks
ax.xaxis.set_major_formatter(DateFormatter('%Y'))

# set years 1992-2007
datemin = datetime.date(1992, 1, 1)
datemax = datetime.date(2007, 12, 31)
ax.set_xlim(datemin, datemax)

labels=ax.get_xticklabels()
setp(labels,'rotation',45,fontsize=10)

legend(loc="upper right", bbox_to_anchor=[0.98, 0.98],
       ncol=1, shadow=True)

pyplot.ylabel('NEE($gC m^{-2} day^{-1}$)')
pyplot.title('Net Ecosystem Exchange')

pyplot.savefig('nee_obs_model_HF_daily.pdf')

# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
#fig.autofmt_xdate()

pyplot.show()
pyplot.close()

1 个答案:

答案 0 :(得分:1)

我认为安德烈索博列夫是对的。当我运行你的脚本时,通过微调,:-),以及日期字段作为日期的一些数据,我得到了几年没有问题。它实际上是您的代码,但以下情况除外:

fh = open(thisFileName)
#  a numpy record array with fields: date, nee, nee_obs
#  from a csv, thisFileName with format:
# Date,nee,nee_obs
# 2012-02-28,137.20,137.72
matplotlib.mlab.csv2rec(fh)
fh.close()
r.sort()
days = r.date
nee = r.nee
nee_obs = r.nee_obs
...
...

然后我得到: NEE Figure

here借来的大部分解决方案。如果我误解了你的需要,请告诉我。