MATLAB Answers


Timestamp on X axis from datetime

Asked by Maksym Zawrotny on 3 Dec 2018
Latest activity Commented on by Maksym Zawrotny on 4 Dec 2018
Hello, I have made a plot already which looks like that:plot1.PNG
X axis is a time of observation. It is a vector of [0, 5, 10, 15 ...]. I would like to use a timestemps as a X axis ticks. I have a variable ts, which is the timestamp of each sample. How should I change my X axis description using a plot browser to timestams. Format of my timestamps is 'dd.MM.yyyy HH:mm:ss'


Sign in to comment.




1 Answer

Answer by Jorik
on 3 Dec 2018
 Accepted Answer

Hi Maksym, if you convert your x vector to a datetime, you can simply plot the datetime vector against your values for the 3 lineplots and already get meaningful labels for the timestamps.
x = today + (0.5:0.01:0.6);
x_datetime = datetime(x, 'ConvertFrom', 'datenum');
plot(x_datetime, rand(size(x)))
As you can see, I start with simple datenum doubles, convert it to datetimes and if you zoom into the plot or use a different time-scale, the x-labels are automatically changed to show meaningful values and details.
If you need the specific format you mentioned, you can specify it with a line like this:
xtickformat('dd.MM.yyyy HH:mm:ss')
All of this is possible since R2016b or do you need to use an older version of MATLAB?


If YourTimestamps is a cell array of character vectors in 'dd.MM.yyyy HH:mm:ss' format, then you would probably want something like
x_datetime = datetime(YourTimestamps, 'InputFormat', 'dd.MM.yyyy HH:mm:ss');
Thank you, Jorik!
It's just the thing I needed.

Sign in to comment.