How to label the x-axis of a time series with the years?

6 ビュー (過去 30 日間)
tng
tng 2021 年 3 月 26 日
コメント済み: tng 2021 年 3 月 26 日
I have a time series that gives data every hour from 1979 January 1st 00:00 am to 2021 March 11th 22:00 pm. So, I have a time series that has 369886 elements in total and it's a row vector. For example, use x= rand(369886,1). How do you show the years on the x axis (using xlabel)?
(i.e, 1979,1980,...,2021 on the x axis taking into account the leap years etc)
I'd highly appreciate an example if it's possible

採用された回答

Chien-Han Su
Chien-Han Su 2021 年 3 月 26 日
In my opinion, you just need to find the index of data corresponding to each year's Jan 1st 0:00 am and label it. My example is as follows
% get data
x=log10(1:369886);
% parameters for the process
listLeapYear1970to2030 = ...
[1972 ,1976, 1980, 1984, 1988, ...
1992, 1996, 2000,2004, 2008, ...
2012, 2016, 2020, 2024, 2028];
hour4Normal = 24*365;
hour4Leap = 24*366;
yearFirst = 1979;
hour4FirstYear = hour4Normal;
% start labeling
labelYear = zeros(size(x));
ind4YearStart = [];
pivot = 0;
yearCurrent = yearFirst
while pivot+1 <= numel(x)
ind4YearStart = [ind4YearStart, (pivot+1)];
labelYear(pivot+1) = yearCurrent;
if ~ismember(yearCurrent, listLeapYear1970to2030) % normal year
pivot = pivot + hour4Normal;
else % l
pivot = pivot + hour4Leap;
end
yearCurrent = yearCurrent+1;
end
yearLast = yearCurrent;
% show data
yearSeparation2Show = 4;
plot(x)
xticks(ind4YearStart(1:yearSeparation2Show:end))
xticklabels(num2str((yearFirst:yearSeparation2Show:yearLast)'))
axis([-inf inf -inf inf])
and the result is like
※Since the data starts also from Jan 1st 0:00 in your case which make thing easier by letting
hour4FirstYear = hour4Normal;
if not, you can modify hour4FirstYear to any other value according to your situation.
※To make the x-axis more easy to read, I only show the year label every 4 years by letting
yearSeparation2Show = 4;
You can adjust the separation when you need
  1 件のコメント
tng
tng 2021 年 3 月 26 日
Woah this is longer than I expected but thank you so much, really appreciate it! I thought there was a shorter way with datenum or datestick but I kept getting errors. This works anyway, so should be fine. Thanks again.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTime Series Events についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by