Can "datetime" be responsible for the misalignment of data in a plot ?

2 views (last 30 days)
I have two types of time vectors, t1 and t2, both indicating a time range of 44 days:
% vector t1
t1 = linspace(0,44,1057);
>> t1
t1 =
1056×1 single column vector
0
0.04166667
0.08333334
0.125
0.1666667
0.2083333
0.25
0.2916667
0.3333333
...
43.83331
43.87498
43.91665
43.95831
% vector t2
a = {'17-Jun-2017'; '30-Jul-2017'};
b = cellstr(datetime(a{1}) : days(1) : datetime(a{end}))
k = 1;
for i = 1:length(b)
for j = 0:23
t2{k} = strjoin([b(i),sprintf('%d:00:00',j)]);
k = k + 1;
end
end
>> t2'
ans =
1056×1 cell array
{'17-Jun-2017 0:00:00' }
{'17-Jun-2017 1:00:00' }
{'17-Jun-2017 2:00:00' }
{'17-Jun-2017 3:00:00' }
{'17-Jun-2017 4:00:00' }
{'17-Jun-2017 5:00:00' }
...
{'30-Jul-2017 19:00:00'}
{'30-Jul-2017 20:00:00'}
{'30-Jul-2017 21:00:00'}
{'30-Jul-2017 22:00:00'}
{'30-Jul-2017 23:00:00'}
When I plot the same data, but with different types of time arrays as x-axis
% I plot both types of times:
subplot(2,1,1);
plot(datetime(t2), Prob);
subplot(2,1,2);
plot(t1, Prob);
I can see that my data in the first subplot and in the second subplot, where I used the two different types of time vectors, are not aligned on the x-axis, i.e. the time-axis (from the red lines that I have added with powerpoint we can see that the same peaks do not correspond in the time-axis).... Can "datetime" be responsible for the misalignment of data ?

Accepted Answer

Star Strider
Star Strider on 18 May 2022
The first cluster of data (at about 2.5 or about 18 Jun) appears to be perfectly aligned in both plots. The datetime plot goes to 05 Aug, while the ‘t1’ plot stops at 45.
See if setting:
xlim([min(t1) max(t1)])
and
xlim([min(t2) max(t2)])
in their respective plots corrects the misalignment.
.
  2 Comments

Sign in to comment.

More Answers (1)

Cris LaPierre
Cris LaPierre on 18 May 2022
I think the allignment difference is due to what MATLAB is setting your axis limits to when the x values are datetimes (Jun 17 - Aug 5, or 50 days) vs when they are doubles (0-45).
Set your axes limits to be the same number of days in both plots, and I'd expect the data to align.
  1 Comment
Sim
Sim on 18 May 2022
Edited: Sim on 18 May 2022
Thanks a lot @Cris LaPierre!
Yes, by adding xlim in both subplots, it works and the data look like aligned (at least with a visual inspection :-) )

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!