How to label the x-axis of a time series with the years?
3 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Time Series Events 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!