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

3

我在特定的场地绘制了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()

2
你的 days 数组是如何构建的? - Andrey Sobolev
能否提供 daysneenee_obs 的一些示例数据?请同时发布您的导入,以便我不必寻找 YearLocatorDateFormatter 来自于 matplotlib.dates,并且可以在 pyplot 中找到 setplegend - BioGeek
1个回答

1

我认为Andrey Sobolev是正确的。当我运行您的脚本时,进行了一些小调整,:-),使用一些日期字段作为日期的数据,年份可以正常显示。这基本上是您的代码,唯一的例外是:

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

这个解决方案的很多内容都借鉴了这里。 如果我对您的需求有误,请告诉我。


感谢回复。我的问题出在日期列表上。我最初使用days=range(1,5844)创建了它,然后尝试使用YearLocator格式化x轴。相反,我编写了一个函数来创建1992年至2007年的日期列表。 - Darren
def create_years(): dates=[]

16年的天数

days=range(0,5843) for i in days: datestart=datetime.date(1992, 1 ,1) dates.append(datestart+datetime.timedelta(i)) #print datestart+datetime.timedelta(i) return dates
- Darren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接