Add dates in x-axis of every graph

6 views (last 30 days)
I am plotting time series graphs with forecasts, forecasts intervals. The following is a part of a for loop which I haven't shown here. There are 4 cstates defined in state_mat. For each state, I plot the forecasts of variables such as var1, var2,.., var5, and time horizon for forecast is 15 periods. Upon running the forloop, the output is 4 graphs for each of those 5 variables. However, right now, the x-axes of the graphs aren't properly labelled. I would like the x-axis to be labeled from 1995-Q1 to 2030-Q4, but the labels aren't appearing each of the graphs. How can I modify the code to ensure that every graph is properly labeled with dates on the x-axes?
% T= 200
% horz = 15
% array_dates = (1 x 215) obs of class datetime
% state_mat = ['RI'; 'MA'; 'NY'; 'CT'];
hold on;
plot(datenum(array_dates(64:T)), y(64:T), 'Color',[0.5,0.5,0.5], 'LineWidth', 1)
datetick('x', 'QQ-YY')
% shock, up_75, down_75, up_95, down_95 are (15 x 1) doubles
plot(datenum(array_dates(T:T+horz)),[y(T); shock],'b','LineWidth',1);
plot(datenum(array_dates(T:T+horz)),[y(T); up_75],'k--','LineWidth',1);
plot(datenum(array_dates(T:T+horz)),[y(T); up_95],'k--','LineWidth',1);
plot(datenum(array_dates(T:T+horz)),[y(T); down_75],'k--','LineWidth',1);
plot(datenum(array_dates(T:T+horz)),[y(T); down_95],'k--','LineWidth',1);
xlim([datenum(array_dates(64)), datenum(array_dates(T+horz))]);
if i < length(state_mat)
set(gca,'xticklabel',{[]});
end

Accepted Answer

Walter Roberson
Walter Roberson on 9 Aug 2022
datetick() is not "sticky": it does a one-time conversion of the xlim range into formatted ticks, or (depending on the option) takes the current tick locations and creates labels for them. datetick() is not a mode.
You need to datetick() at the end of your plots.
Also setting xticklabel to empty would undo any active tick labels.
Question: why are you using datenum() and datetick() ? Why are you not using datetime() objects? For several years, plot() has supported automatic labeling when you pass in datetime objects.
  1 Comment
alphabetagamma
alphabetagamma on 12 Aug 2022
Thank you so much for the suggestion, and sorry for not replying sooner. You are right. I wasn't aware, and so I've modifed my code as such.

Sign in to comment.

More Answers (0)

Categories

Find more on Labels and Annotations 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!