MATLAB: How to use custom date labels for the x-axis in MATLAB plots

axisdatetickMATLABplotxtickxticklabel

How can I use custom date labels for my x-axis?
I am using "datetick" to show the dates in the x-axis. However, I only want to show 3 ticks: the left-most, middle and right-most ticks.
How can I modify my script so that I get this behavior?
>> figure
>> box on
>>
>> % Start, end and number of ticks...
>> startDate = 7.3457e+05;
>> endDate = 7.3458e+05;
>> numbertick = ceil(endDate - startDate);
>>
>> % Plot them
>> xData = linspace(startDate, endDate, numbertick);
>> plot(xData,ones(size(xData)));
>> datetick('x')

Best Answer

It is more convenient to format the tick labels using the "XTick", "XTickLabelMode" and "XTickLabel" properties of the axis object (vs. using "datetick" function):
>> figure
>> box on
>>
>> % Start, end and number of ticks...
>> startDate = 7.3457e+05;
>> endDate = 7.3458e+05;
>> numbertick = ceil(endDate - startDate);
>>
>> % Plot them
>> xData = linspace(startDate, endDate, numbertick);
>> plot(xData,ones(size(xData)));
>>
>> %%Modify the axes properties
>> set(gca, 'XTick',xData)
>> set(gca, 'TickDir', 'out');
>> set(gca, 'XTickLabelMode', 'auto');
>>
>> % Modifying the labels
>> labels = get(gca, 'XTickLabel');
>>
>> for i = 1:length(labels)
>> if i == 1 || i == ceil(length(labels)/2) || i == length(labels)
>> labels{i} = datestr(xData(i), 'mm/dd');
>> else
>> labels{i} = '';
>> end
>> end
>>
>> set(gca, 'XTickLabel', labels)