How to set the axis to display hours?

How can I make the datetick count from 00:00 to 23:59. This below is dispalying 00:00 for every hour.
d= datetime(start_date):1/24:datetime(end_date)+1;
hours=hour(d);
scatter(hours,rand(size(d)));
t=datenum(d);
ax=gca;
ax.XTick=1:24;
datetick(ax,'x','HH:MM','keeplimits','keepticks')

Answers (1)

The XTick values need to be date number for datetick to work, so maybe:
ax.XTick = ceil(ax.XLim(1)):1/24:floor(ax.XLim(2));
datetick(ax,'x','HH:MM','keeplimits','keepticks');

5 Comments

Thanks Guillaume. Is this line not converting to date numbers >>t=datenum(d);?
The lines you provided display a black thick line on the x axis.
Yes, it does, but you're not using it afterward. So, yes another option would be:
t = datenum(d);
scatter(t, rand(size(d)));
datetick(gca,'x','HH:MM','keeplimits','keepticks')
But you may have way more than 24 ticks depending on the number of hours between start_date and end_date. Moreover, if start_time does not fall exactly on the hour, your ticks won't either.
My solution produces a tick exactly every hour, for each hour. If you have lots of hours then they all overlap and you get a sort of thick black line. I wasn't sure you wanted a tick every hour, or just 24 ticks. If just 24 ticks:
ax.XTick = linspace(ceil(ax.XLim(1)), floor(ax.XLim(1)), 24);
edit: typo
Thanks again Guillaume. Yes, I want just 24 ticks, from 00:00 to 23:59 so that i can be able to use it to plot measured data for the whole day (and for each day) for a given range of days. the last line gives this error:
>>ax.XTick = linspace(ceil(ax.XLim(1)), floor(ax.XLim(1), 24)); Error using floor Too many input arguments.
Yes, there was a typo, missing a bracket which you added in the wrong place. I've corrected my answer
>> d= datetime(start_date):1/24:datetime(end_date)+1;
>> hours=hour(d);
>> t=datenum(d);
>> scatter(hours,rand(size(d)));
>> ax=gca;
>> ax.XMinorTick='on';
>> ax.XTick = linspace(ceil(ax.XLim(1)), floor(ax.XLim(1)), 24);
While setting the 'XTick' property of Axes: Value must be a vector of type single or double whose values increase
Now it says the vector values aren't increasing. Sorry I can figure this out.

Sign in to comment.

Categories

Asked:

ccs
on 26 Feb 2015

Commented:

ccs
on 27 Feb 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!