MATLAB: Consistent datetick labels for series of winter plots, 2001-2017

datenumdatetickdatetimeMATLABx-axis label

Hi There,
I'm making a series of seventeen daily time series plots, one for each winter 2001-2017 and cannot get the x-axis labels to display consistently across plots. I want each x-axis label to start on Nov 1st, end on April 30th, and mark the first day of each month in between. Data from 2011/2012 and 2012/2013 attached.
Edit: Matlab R2016a
I'm using datetime, datenum, and datetick:
yr = 1850:2050 % inclusive of a long time series, but i'm only using 2001-2017 for now
startYear = 2001;
endYear = 2017;
for i = 1:length(startYear:endYear)-1
yri = find(yr==startYear+1-1) % Nov/Dec year
<snip> % code for identifying leap years in my y-data
t1 = datetime(startYear+i-1,11,1,0,0,0) % Nov. 1st of startYear
t2 = datetime(startYear+i,4,30,0,0,0) % Apr. 30th of following year
t = t1:days(1):t2;
xDate = datenum(t); x-data for x-axis labels
<snip> % more y-data processing
figure(i);
clf
set(gca,'FontSize',20)
plot(xDate,ydata)
set(gca,'YLim',[-30 30]); % all plots have same y limits
set(gca,'Xlim',[min(xDate) max(xDate)]) % all plots start Nov. 1, end Apr. 30
datetick('x','mmm','keepticks','keeplimits')
end
I've attached examples of the resulting plots. Note that neither plot starts on November 1st or ends on April 30th. There is some sort of rounding going on that I can't figure out how to fix.
Any tips or help appreciated.

Best Answer

I didn’t use a datetime array here and used the older date formats instead. This does what you want for the sample data I plotted.
The Code
dnv = datenum([2016 10 31]):datenum([2017 04 30]); % Date Number Vector
dvm = datevec(dnv); % Date Vectors (For End-Of-Month Calculation)
dmm = unique(dvm(:,1:2), 'rows'); % Unique Years & Months
eoms = eomday(dmm(:,1),dmm(:,2)); % Find End-Of-Month Days
xtix = datenum([dmm eoms]); % Date Numbers For End-Of-Month Days
xtix(1:end-1) = xtix(1:end-1)+1; % Add ‘1’ To All But Last
xdata = dnv(2:end); % Create Data
ydata = rand(1, length(xdata))*10 - sin((0:length(xdata)-1)*pi/length(xdata))*25 + 10;
figure(1)
plot(xdata, ydata)
grid
set(gca,'YLim',[-30 30])
set(gca, 'XTick',xtix)
datetick('x', 'mmm dd', 'keepticks')
Your files contain only the dependent variable, so it will probably be relatively straightforward for you to adapt my code here to your data by substituting it for ‘ydata’.
The Plot