Search code examples
matlabdatetimeplotformattingmatlab-figure

Setting time ticks in a MATLAB plot


On the x-axis of my plot should be the time and on the y-axis the value. For each value I have a time stamp in milliseconds. I would like to have on the x-axis a tick every say 5 minutes, say 16:05, 16:10, 16:15 and so on. The time distance between the values is not equal.

How can this be done?

An example of a data vector is (first column timestamp, second column value):

27634517312999, 1.1111809015274048
27658503234656, 0.7998865246772766
27662988099446  0.7806665897369385
27664499628612  0.7781039476394653
27950691973920  0.8562135696411133
27970195902662  0.8036822080612183
27973194252661  0.7908696532249451
....

I think I have to be more clear. Each value has an assigned absolute timestamp in milliseconds which represents the time elapsed from 1970 (I think). I have gathered this values by System.currentTimeMillis() call from Java. For example 27658503234656 corresponds to Mon Jun 18 2846 14:33:54 GMT+0100. The values span rougly a range of one hour (the same year, day etc.). That means the first timestamp is 27658501657000 (representing Mon Jun 18 2846 14:07:37 GMT+0100) and the last timestamp is 27658504995000 (representing Mon Jun 18 2846 15:03:15 GMT+0100). I'm only interested in 14:07 until 15:03. On my x-axis the first label should be at 14:10 and then there should be labels every 5 min, i.e. 14:15, 14:20 etc. The last label is at 15:00.

How can this be done?


Solution

  • The answer by Adriaan using datetick should be the easy solution. If you like to control the level of detail by yourself, you could do something like:

    % suppose data is your matrix (n x 2)
    t = data(:,1) / 1000 / 3600 / 24; % time from ms to days
    plot(t, data(:,2), '+-');
    ticks = linspace(min(t), max(t), 5); % 5 ticks from min to max
    labels = datestr(ticks, 'HH:MM'); % get only hours and minutes
    set(gca, 'xtick', ticks, 'xtickLabel', labels);