xticks not working properly when combined with datetick
2 views (last 30 days)
Show older comments
I have a dataset where I receive time in seconds and some data "y". I want plot time against my "y" data. I then wanted to change the tick marks the plot's x-axis to the format of 'HH:MM:SS', so I converted the time using "datenum" and then used "datetick". However, I also wanted only 2 tick marks on the plot and 05:00:00 and 15:00:00 so I used "xticks" as shown below. When I use the command "xticks(t_ticks_serial)", rather than getting tick marks at 05:00:00 and 15:00:00, I get tick marks of xticks(1) and xticks(2) at the locations where 05:00:00 and 15:00:00 should be. I've used xticks before without using datetick, and from my understanding this is not what should be happening so I was a bit confused. Am I doing something wrong here?
t = seconds([0:3600:82800]); % time in seconds at 1-hour intervals from 0000-2300
t_serial = datenum(datestr(t, 'HH:MM:SS.FFF'), 'HH:MM:SS.FFF'); % convert time from seconds to datenum
y = [1:1:length(t_serial)];
plot(t_serial, y)
datetick('x', 'HH:MM:SS');
t_ticks = seconds([5*3600 15*3600]); % 05:00:00 and 15:00:00 in seconds
t_ticks_serial = datenum(datestr(t_ticks, 'HH:MM:SS.FFF'), 'HH:MM:SS.FFF');
xticks(t_ticks_serial)
0 Comments
Answers (1)
Walter Roberson
on 5 Nov 2020
xticks() first, and then datetick() with 'keepticks' option.
2 Comments
Walter Roberson
on 6 Nov 2020
No. datetick() does not set up a condition forcing anything upon future label content or positions. Instead, datetick works entirely by figuring out "nice" positions, setting xtick to them, and then setting xticklabels -- and then it stops. No property is set that controls what happens in the future.
In particulary, if you zoom or pan and would thus be wanting a new set of date ticks to be generated, then that simply does not happen automatically: you have to have added a datetick call into a ResizeFcn callback or a Zoom or Pan event listener.
Therefore if you are going to use datetick and you want particular tick locations, you have to set them first, and then call datetick later.
There are a couple of work-arounds:
- don't use datetick: set your ticklabels yourself to whatever text. If you do this you have the same zoom/pan limitations of needing to do the updating of the tick positions and labels yourself; OR
- don't use datetick and don't use datenum for your axes; use datetime() objects instead. datetime() objects for an axes create a different kind of internal axes that does know to update automatically.
These days I would have to have fairly solid reasons to use serial date numbers as axes instead of using datetime or duration objects.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!