Plotting data on time (date) axis

It seems like it might be the best to use datetick.

Usage: datetick('x') or datetick('x', dateformat) with the available formats as explained in the documentation.


Assuming your data file has the format given above, you could use textscan to read the data:

fid = fopen('data.txt','rt');
C = textscan(fid,'%s %s %s %d','Delimiter','.','CollectOutput',1);
fclose(fid);

The first cell of C will contain an N-by-3 cell array of strings (the parts of the date) and the second cell of C will contain an N-by-1 vector of the data measurements. You can create a date number for each measurement by first concatenating the 3 smaller strings into one date string and then using the datenum function:

t = datenum(strcat(C{1}(:,3),'-',C{1}(:,2),'-',C{1}(:,1)));
data = C{2};

Once you have a vector of date numbers t to go with your vector of measurements data, you can then plot them:

plot(t,data,'*');  %# Plot the points as asterisks

Now, you can change the x-axis labels to show the actual dates. One option is to use the function datetick, an easy and elegant solution given in steven's answer. Another option is to use the function datestr to create the labels yourself, then modify the XTick and XTickLabel properties of the current axes:

xpts = min(t):max(t);  %# Make a full vector, filling in missing dates
set(gca,'XTick',xpts,'XTickLabel',datestr(xpts));  %# Set axes properties

NOTE: Whichever option you choose for changing the x-axis labels to date strings, you may run into trouble with the labels overlapping each other if the tick marks are too close together. You could fix this by reducing or repositioning the tick marks along the x-axis (by changing the XTick property) or by adjusting the axes FontSize property. If you wanted to rotate the labels to make them fit, you would have to erase the labels and create new rotated text objects for them. The following submission on The MathWorks File Exchange does just that:

  • Rotate Tick Label by Andrew Bliss

With datenum you can convert any string date into numerical format based on the date format symbols (see help datestr).

For example all this leads to the same numerical date representation:

datenum('15/05/2009 21:22','dd/mm/yyyy HH:MM');
datenum('15.05.2009 21:22','dd.mm.yyyy HH:MM');
datenum('21-22 15.05.2009','HH-MM dd.mm.yyyy');
datenum('21-22 05/15.2009','HH-MM mm/dd.yyyy');
...

The nice thing is that you can pass cell array (output from textscan) or char array directly to datenum and it will output numeric date array.