Clear Filters
Clear Filters

Finding start dates and end dates of a year and plot them

16 views (last 30 days)
I have this code
t=datetime(2017,1,1) + hours(1:8760); % terminals per hour for the whole year
plot(t, y); % plot the the data versus year's hours
MidleMonths = datetime(year,1:12,15); % desired tick locations, as datetimes
set(gca, 'xtick', MidleMonths);
hold on
I want to:
  1. determine the start date and end date of each month in the above year.
  2. Then, plot dotted lines on the start dates and end dates of the months of the above year.
  3. There is no magnitude (Y values) for the dotted lines (start and end dates). The dotted lines will go to infinity (up to the top of the image).
How can I do it please?
See the target figure ( this dotted lines done on PowePoint)

Accepted Answer

Cris LaPierre
Cris LaPierre on 8 May 2020
I would suggest looking into the following functions
  1. dateshift - to shift a date to the start of the month
  2. calmonths - to increment the start date by exactly one month
  3. xline - create a vertical line that continues to infinity
Here's a dummy example to get you started
t=datetime(2017,1,1) + hours(1:8760); % terminals per hour for the whole year
% ignore code for y. Just recreating a shape similar to the original plot
y = 30-(([1:length(t)]-4380).^2)/1e6 + 15*rand([1,length(t)]);
plot(t, y); % plot the the data versus year's hours
% Create vector of dates from start of the first month to end of t incrementing by 1 month
mStart = dateshift(min(t),"start","month"):calmonths(1):max(t)
% Add vertical line for start of each month
for l = 1:length(mStart)
% Set display format of dates on x-axis
xtickformat(gca,"MMM yy")
Cris LaPierre
Cris LaPierre on 11 May 2020
Not sure how far you got. Here's how I might do it.
% determine where to put vertical lines
mStart = dateshift(min(t),"start","month"):calmonths(1):max(t);
% get a unique color for each month using the jet colormap
C = jet(length(mStart)-1);
for l = 1:length(mStart)
% Add colored patch for each month.
if l>1
% Get 4 X coordinates for patch
xBox=[d1 d2 d2 d1];
% Get 4 Y coordinates for patch
yBox=sort([get(gca,'YLim') get(gca,'YLim')]);
% Add patch. Set transparency by adjusting FaceAlpha.
hold on
hold off
HG-NU on 11 May 2020
Thanks Cris, for your amazing assistance. I really appreciate it all.

Sign in to comment.

More Answers (0)


Find more on 2-D and 3-D Plots in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!