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

조회 수: 4 (최근 30일)
Elizabeth
Elizabeth 2017년 5월 1일
댓글: Star Strider 2017년 5월 1일
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.

채택된 답변

Star Strider
Star Strider 2017년 5월 1일
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
  댓글 수: 2
Elizabeth
Elizabeth 2017년 5월 1일
Lovely, this worked perfectly. Did not know about eomday function, super useful.
Star Strider
Star Strider 2017년 5월 1일
As always, my pleasure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Christmas / Winter에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by