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

1 回表示 (過去 30 日間)
Sim
Sim 2022 年 5 月 17 日
コメント済み: Star Strider 2022 年 5 月 18 日
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 ?

採用された回答

Star Strider
Star Strider 2022 年 5 月 18 日
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 件のコメント
Sim
Sim 2022 年 5 月 18 日
Thanks a lot @Star Strider !
By adding xlim, it now seems to be correct:
subplot(2,1,1);
plot(datetime(t2), Prob);
xlim([min(datetime(t2)) max(datetime(t2))])
subplot(2,1,2);
plot(t1, Prob);
xlim([min(t1) max(t1)])
Star Strider
Star Strider 2022 年 5 月 18 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Cris LaPierre
Cris LaPierre 2022 年 5 月 18 日
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 件のコメント
Sim
Sim 2022 年 5 月 18 日
編集済み: Sim 2022 年 5 月 18 日
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 :-) )

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAxis Labels についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by