Why my axis have wrong startung date?

I have used the following code to plot the returns of an index over the time. I have 118 months of returns for each stock. I used start date and and date. When I use datestr I obtain the right dates but I don't knwo why the plot starts from Nov 2006, and I can't understand why and where does it takes that label. Hope someone can help me. I paste my code and attach the plot I obtain. Code:
startDate = datenum('Nov-30-2007');
endDate = datenum('Sep-30-2017');
xData = linspace(startDate,endDate,118);
y=index;
plot(xData, y);
str = datestr(xData, 'mmm yyyy');
NumTicks = 93;
L = get(gca,'XLim');
set(gca,'XTick',linspace(L(1),L(2),NumTicks))
datetick('x','mmm yyyy','keeplimits', 'keepticks')
set(gca,'XMinorTick','on','YMinorTick','on')
xticklabel_rotate;
axis([xData(1) xData(118) -5 8])

Risposte (1)

I think the following line in your code is causing this problem.
set(gca,'XTick',linspace(L(1),L(2),NumTicks))
You should replace this line by the following.
set(gca,'XTick',linspace(xData(1),xData(end),NumTicks))

2 Commenti

Thank you a lot! Now the starting date on the axis is correct but why does the plot starts before the starting date?
Walter Roberson
Walter Roberson il 15 Nov 2017
Modificato: Walter Roberson il 15 Nov 2017
You are using serial date numbers as your x axis, and you have a fair range of them (over 3500). When creating plots with automatic scaling, MATLAB does not put the lowest x value as being the beginning of the x axis: MATLAB instead rounds so that "nice" numbers are used.
For example if you plotted with x = 23:517 then the plot will not by default start at 23 and end at 517: MATLAB will start the plot at 0 and end at 600 .
It happens that nice "round" numbers for the serial date number span you are using happen to extend back to the year before your data of interest -- a span in serial date numbers from 733000 to 737000.
If you have R2016b or later then I would recommend that you switch to using datetime objects as your axes.

Accedi per commentare.

Categorie

Tag

Richiesto:

il 14 Nov 2017

Modificato:

il 15 Nov 2017

Community Treasure Hunt

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

Start Hunting!

Translated by