Reputation: 253
I have a graph where the x-axis is a vector from 1
to 1440
(the number of minutes in a day). I would like to know if there is some way I can use hours on the x-axis while still using each value in the vector.
For Example:
1 would be marked 12 AM
60 would be marked 1 AM
Upvotes: 1
Views: 755
Reputation: 4768
If you don't mind changing your plotting code slightly, you could use datetick
, which converts the labels on a given axis to dates. You can do the following
x = 1:1440;
y = rand(1,1440);
plot(x/1440,y); % dividing minutes by 1440 is the same as converting to datenum
datetick('x','HHPM');
datetick
also gives you the option to 'keeplimits'
or 'keepticks'
, which preserves the limits and ticks of the existing plot respectively. You can change the tick labels by changing the format string. The string above combines the 'HH'
format, which is the hour of the day (24-hr by default) with the 'PM'
format, which converts the hours to 12-hour format and appends AM or PM as appropriate. You can read the datetick
documentation for all of the possibilities.
Upvotes: 1
Reputation: 11792
An option would respect your original tick
location but convert them to the format you want:
set( gca , 'XTickLabel' , datestr( (get(gca,'XTick')/1440) , 'HH:MM PM' ) )
You can look the datestr
help page to see all the other formats you can use (if you want to remove the display of the minutes for example).
Note: Be aware that this will only change the text of the existing tick marks for a given view. It does not force the ticks at one given position (just uses the current ones), and it becomes invalid as soon as you zoom in or out. It means you have to recall the instruction every time you change the axis X-limits.
Upvotes: 0
Reputation: 112659
labels = {'12 AM', '1 AM', '2 AM', '3 AM' ...
'4 AM', '5 AM', '6 AM', '7 AM' ...
'8 AM', '9 AM','10 AM','11 AM'...
'12 PM', '1 PM', '2 PM', '3 PM' ...
'4 PM', '5 PM', '6 PM', '7 PM' ...
'8 PM', '9 PM','10 PM','11 PM'};
set(gca, 'xtick', 1:60:1440);
set(gca, 'xticklabel', labels);
Upvotes: 2