Search code examples
matlabmatlab-figureaxisaxis-labels

How to best set date axis in Matlab


Could you help me regarding setting the date axis in Matlab or point me to the right post?

My problem is the following: I have a few prices and dates in number format that I want to plot, for example:

 Prices = repmat([10; 5; 3; 4; 11; 12; 5; 2],10,1);

 Dates = [726834:726834+8*10-1]';

If I plot them like this:

 plot(Dates,Prices)
 dateaxis('x',17)

I get x-axis values that I don't want, because they look irregular (I guess they follow certain rules but they don't look nice). How can I best set them to, e.g., always the first of the month, or first of January and first of July, or such? I know that I can probably use set(gca, 'xtick', ?? ??); but I lack some overview of how exactly I can do this and the Matlab help doesn't help me.


Solution

  • This code labels the plot with the first day of every month. To get every January or July, only certain elements of the month array should be selected. The strategy is to get every last day of the month using eomdate and add by 1. Figure 1 gives you the first day of each month, and Figure 2 gives you the months you select in the array months_to_display.

    Prices = repmat([10; 5; 3; 4; 11; 12; 5; 2],10,1);
    
    Dates = [726834:726834+8*10-1]';
    
    firstDate = strsplit(datestr(Dates(1)-1, 'dd,mm,yyyy'),',');
    lastDate = strsplit(datestr(Dates(end), 'dd,mm,yyyy'),',');
    
    months = mod(str2double(firstDate{2}):str2double(lastDate{2})+12*(str2double(lastDate{3})-str2double(firstDate{3})),12);
    months(months == 0) = 12;
    
    years = zeros(1,length(months));
    currYear = str2double(firstDate{3});
    for i = 1:length(months)
        years(i) = currYear;
        if (months(i) == 12)
            currYear = currYear + 1;
        end
    end
    
    dayCount = eomdate(years,months);
    firstDates = dayCount+1;
    
    figure(1)
    plot(Dates, Prices)
    xticks(firstDates);
    xticklabels(datestr(firstDates));
    
    months_to_display = [1 7];
    months_to_display = months_to_display - 1;
    months_to_display(months_to_display == 0) = 12;
    months_to_collect = ismember(months, months_to_display);
    
    months = months(months_to_collect);
    years = years(months_to_collect);
    
    dayCount = eomdate(years,months);
    firstDates = dayCount+1;
    
    figure(2)
    plot(Dates, Prices)
    xticks(firstDates);
    xticklabels(datestr(firstDates));