Timestamps on X axis from datetime
10 views (last 30 days)
Show older comments
minh lan on 20 Oct 2019
Commented: Peter Perkins on 30 Oct 2019
Hello, I have made a plot already which looks like that
X axis is a time of observation with step is 1 minutes from 17:00 of previous day to 14:00. How can I change my X axis description to timestampsamps. Format of my timestamps is 'HH:MM'.
I tried to use datetick but this gives a time of "12:00:00 AM" across the entire axis.
dpb on 20 Oct 2019
You've got to create datenum array to match to plot against for datetick to work correctly. Or you need to plot the x axes using datetime values instead. It depends on how the plot data are created to determine which is easier...if you just have numeric data at each time point, then datetime is trivial--if there's a curve fit against time in seconds using fit as in (I'm presuming) the other very similar Q? by a different monikor, then the second axes is probably easier...
ymd=clock; ymd=ymd(1:3); % get a date for strarters for datenum reference
dn=datenum(ymd(1),ymd(2),ymd(3),-7,[0:21*60].',0); % datenum vector by minute between stated limits
% Show what got sidebar...
%>> datestr([dn(1) dn(end)])
% ans =
% 2×20 char array
% '19-Oct-2019 17:00:00'
% '20-Oct-2019 14:00:00'
% Continuing from there
hAx=gca; % get the current axes handle
hAx(2)=axes('Position',hAx.Position); % make second axes
hAx(1).XTick=; % hide the first axes tick locations
plot(hAx(2),dn,randn(size(dn))) % add the datenum axes values
datetick(hAx(2),'x','HH:MM','keeplimits') % and turn second axes display to time format
From here you can modify axes limits and other properties as desired. Just remember have to keep the two in synch as to how many points are shown and that the limits of how many seconds are shown in the first are those that correspond to the correct time in the second.
If you have a way to generate the y data versus a datetime; it's the simpler solution as would only have the one axes and the dates would be incorporated directly.
Peter Perkins on 30 Oct 2019
Ideally, tyr not to resort to using datenums and datetick. To expand on dpb's mention of datetime plotting, this
>> t = datetime(2019,10,30)+days(rand(100,1));
>> y = rand(100,1);
just works in anything like a recent version of MATLAB.
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!