Using datetick with keepticks in MATLAB

641 views Asked by At

I'd like to display an array at length (24*60*60). The x axis is the time of a day.

When I use the following code, x axis shows 00:00:00, 00:59:59, 01:59:59, ..., 23:59:59, but there is no plot on the figure. That is plot(1:length(A),A) has no effect. (I also tried turning on/off hold switch, and 24/24+1)

A = rand(1,86400);
x0 = datenum('00:00:00','HH:MM:SS');
x1 = datenum('23:59:59','HH:MM:SS');
xData = linspace(x0,x1,24+1);
plot(1:length(A),A);
set(gca,'XTick',xData);
datetick('x','HH:MM:SS','keepticks');

When I try the following code, plot can be displayed properly. However, the x axis becomes 00:00:00, 02:24:00, 04:48:00, ..., 21:36:00, 00:00:00

A = rand(1,86400);
x0 = datenum('00:00:00','HH:MM:SS');
x1 = datenum('23:59:59','HH:MM:SS');
xData = linspace(x0,x1,86400);
plot(xData,A);
datetick('x','HH:MM:SS','keepticks');

I also tried this version

A = rand(1,86400);
x0 = datenum('00:00:00','HH:MM:SS');
x1 = datenum('23:59:59','HH:MM:SS');
xData = linspace(x0,x1,86400+1);
plot(xData,[A,0]);
datetick('x','HH:MM:SS','keepticks');

The x axis is still 00:00:00, 02:24:00, 04:48:00, ..., 21:36:00, 00:00:00, and the plot can be displayed normally.

Is there any way to set the x axis to become 00:00:00, 01:00:00, 02:00:00, ..., 23:00:00, 00:00:00 or 00:00:00, 00:59:59, 01:59:59, ..., 23:59:59?

Thanks a lot!

1

There are 1 answers

0
TroyHaskin On BEST ANSWER

The problem arises from first plotting on the interval [1,numel(A)] and then setting the ticks at [xData(1),xData(end)].

You can fix this by plotting A within the range of xData:

A = rand(1,86400);
x0 = datenum('00:00:00','HH:MM:SS');
x1 = datenum('23:59:59','HH:MM:SS');
xData = linspace(x0,x1,24+1);
plot(linspace(x0,x1,numel(A)),A);     % change here
set(gca,'XTick',xData);
datetick('x','HH:MM:SS','keepticks');

Also, adding the line

set(gca,'XTickLabelRotation',45); % or some angle

improves the readability of the tick labels.