![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/563246/image.jpeg)
How to label the x-axis of a time series with the years?
8 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Chien-Han Su
on 26 Mar 2021
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/563246/image.jpeg)
※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
More Answers (0)
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!