简体   繁体   English

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

[英]Setting min/max years on x-axis using matplotlib

I have plotted a timeseries of carbon fluxes over 16 years at a particular site. 我已经在特定地点绘制了超过16年的碳通量的时间序列。 I would like the x-axis to have years (1992-2007) instead of year number (1-16). 我希望x轴有年(1992-2007)而不是年数(1-16)。 When I set the x-axis to have a min value of 1992 and a max value of 2007, the graph doesnt appear on the plot, but when I dont set the min/max years, it appears. 当我将x轴设置为最小值为1992且最大值为2007时,图形不会出现在图表上,但是当我没有设置最小/最大年份时,它会出现。 I'm not sure what I am doing wrong. 我不确定我做错了什么。 I plotted another timeseries over one year and was able to label the x-axis with the months using MonthLocator, but am having no luck with YearLocator. 我在一年内绘制了另一个时间序列,并且能够使用MonthLocator标记x轴与月份,但是我没有使用YearLocator。 Here is the code that I have written: 这是我写的代码:

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()

I think Andrey Sobolev is right. 我认为安德烈索博列夫是对的。 When I run your script, with minor adjustments, :-), with some data the I have with the date field as a date, I get the years to show up with no problems. 当我运行你的脚本时,通过微调,:-),以及日期字段作为日期的一些数据,我得到了几年没有问题。 It's virtually your code, with the exception of: 它实际上是您的代码,但以下情况除外:

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
...
...

and then I get: 然后我得到: NEE图

Much of this solution what borrowed from here . 这里借来的大部分解决方案。 Let me know if I misinterpreted what you need. 如果我误解了你的需要,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM