peteron30
peteron30

Reputation: 77

How to I set up x-axis using year-month as tickmarks in matplotlib?

I have a 2D variable XVAR from a netcdf file, with dimension [year, month]. I want to plot the flattened XVAR (1D array with length nyear*nmonth) and set up the x-axis as this: years on major ticks, and months on minor ticks. The difficulty is that I donot know how to create a 1d array at monthly step. There is no monthdelta method that I could use (though I understand that the reason is because each month has different numbers of days).

In the delta=? step below, I tried delta=relativedelta.relativedelta(months=1), but got an error "object has no attribute 'total_seconds'", which I donot completely understand.

import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from mpl_toolkits.basemap import Basemap
from datetime import date, timedelta

ncfile = Dataset('filepath',mode='r')
XVAR4d = ncfile.variables['XVAR'][:]
XVAR2d = np.nanmean(XVAR4d,axis=(2,3)).flatten()
yrs = ncfile.variables['YEAR']

stt = date(np.min(yrs),1,1)
end = date(np.max(yrs)+1,1,1)
delta = ?
dates = mdates.drange(stt,end,delta)

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month   
yearsFmt = mdates.DateFormatter('%Y')

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(yearsFmt)
ax1.xaxis.set_minor_locator(months)
ax1.set_xlim(stt,end)
ax1.plot(dates,xvar2d,c='r')

Upvotes: 1

Views: 1635

Answers (1)

Douglas Dawson
Douglas Dawson

Reputation: 556

I decided I did like the idea of my second comment, so I am turning it into an actual proposed answer.

Instead of using drange, create the dates yourself:

totalMonths = 12*(np.max(yrs) - np.min(yrs)+1)
dates = mdates.date2num([date(np.min(yrs)+(i//12),i%12+1,1) for i in range(totalMonths)])

Upvotes: 1

Related Questions