Reputation: 645
In MATLAB or Octave, my data has the following format for date/time values:
12:00:34.626 AM 2/26/2017
where it is HH:MM:SS:SSS [A or P]M [M]M/DD/YYYY
I want to use it for my x-axis on my plots, and I have tried using datetick, datenum, and datestr and haven't been able to get any of them to work with this format.
How can I use this formatted value string to label my x-axis datapoints?
Upvotes: 2
Views: 12973
Reputation: 1389
Another example is this.
date={'12:00:34.600 AM 2/26/2017','12:00:34.700 AM 2/26/2017','12:00:34.800 AM 2/26/2017','12:00:34.900 AM 2/26/2017'};
timeFormat='HH:MM:SS.FFF AM mm/dd/yyyy';
xdatenum=datenum(date,timeFormat);
data=0:3;
plot(xdatenum,data)
datetick('x',timeFormat,'keepticks')
view([-20,90])
I tilted the plot a little to avoid overlap of x ticks.
You can control the number of ticks by using tick properties.
date={'12:00:34.600 AM 2/26/2017','12:00:34.700 AM 2/26/2017','12:00:34.800 AM 2/26/2017','12:00:34.900 AM 2/26/2017'};
timeFormat='HH:MM:SS.FFF AM mm/dd/yyyy';
xdatenum=datenum(date,timeFormat);
data=0:3;
plot(xdatenum,data)
datetick('x',timeFormat,'keepticks')
set(gca,'XTick',[min(xdatenum) max(xdatenum)])
set(gca,'XTickLabel',[date(1),date(end)])
Here, I made just two ticks with minimum date and maximum date.
Upvotes: 1
Reputation: 10450
You can use the following format:
d = datetime('12:00:34.626 AM 2/26/2017','InputFormat','hh:mm:ss.SSS a M/dd/yyyy')
result:
d =
26-Feb-2017 00:00:34
and if you want to see also the fractions of a second:
>> d.Second
ans =
34.626
For multiple dates strings, stored in a cell array, just replace the string '12:00:34.626 AM 2/26/2017'
above with the cell array.
Then you just write plot(d,y)
(where y
is your data) and you get the x-axis in a time format. You can further customize this format by using the DatetimeTickFormat
property:
plot(d,1,'DatetimeTickFormat','hh:mm:ss.SSS a M/dd/yyyy')
And you will get:
Upvotes: 1
Reputation: 51
I would use a combination of these functions, namely datnum followed by datetick after plotting.
First off your formating string need to be: 'HH:MM:SS.FFF AM mm/dd/yyyy'.
See the following if you need to change format: https://au.mathworks.com/help/releases/R2016b/matlab/ref/datenum.html#inputarg_formatIn
Then use datetick to convert to nice format on plot. https://au.mathworks.com/help/releases/R2016b/matlab/ref/datetick.html
So to a single data point= plot you might have:
xdatestr=['12:00:34.626 AM 2/26/2017'; '12:00:34.626 PM 2/26/2017']
xdatenum=datenum(xdatestr,'HH:MM:SS.FFF AM mm/dd/yyyy')
plot(xdatenum,[0 1])
datetick(gca)
Also note datetime, is whole seperate way of doing it, and uses a different format string convention. http://au.mathworks.com/help/matlab/ref/datetime.html
Upvotes: 2