Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting min/max years on x-axis using matplotlib

I have plotted a timeseries of carbon fluxes over 16 years at a particular site. I would like the x-axis to have years (1992-2007) instead of year number (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. 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. 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()
like image 873
Darren Avatar asked Sep 26 '26 05:09

Darren


1 Answers

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 Figure

Much of this solution what borrowed from here. Let me know if I misinterpreted what you need.

like image 111
macduff Avatar answered Sep 27 '26 18:09

macduff