How to insert sequential dates in the x axis of a plot
Show older comments
Hi all, I am pretty new to Matlab so excuse me the silly question.
I have plotted the following graph:
plot(weightsP1)
xlabel('Monthly Dates')
ylabel('Optimal Weights')
legend('y =1-Month T-Bill Weight','y =S&P 500 Weight')
Now I do not want the x axis to display numbers ranging from 0 to 160 (since weightsP1 is a 160x2 matrix) but I would like to have the dates in the Month Year format.
My x axis should go from Jan 2003 to Apr 2016, but I just want few of the 160 dates to be displayed on the actual x axis.
I would finally like to have my y axix ranging from -3 and 3.
Is there anyone able to help me out with this? I would really appreciate your help.
Thanks in advance,
Federico
Accepted Answer
More Answers (1)
Peter Perkins
on 31 Mar 2017
If you're using a recent version of MATLAB, create your dates as datetimes, not datenums, and just call plot. You get the dates along the axis "for free", and you can specify their format. You'll have to make weightsP1 into a table (or for R2016b or later, a timetable), but I think you'll be happier in the long run. Something like
weightsP1 = array2table(weightsP1,'VariableNames',{'Date','X'})
weightsP1.Date = datetime(weightsP1.Date,'ConvertFrom','datenum')
plot(weightsP1.Date,weightsP1.X)
Categories
Find more on Time Series Objects 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!