How to create a date starting from a specific date and time line for x axis
Show older comments
I have a data set for temperature staring from 2/6/2021 7:12 a.m .
I need to create a x axis with a date starting from 2/6/2021 7:12 a.m to 2/7/2021 1:31 pm. with one minute changes. size of the date line should be 1100
this x axis only need to show the time
and then I need to plot this x axis aginst my temperature labeling with 6 hour intervals.
Answers (1)
Samayochita
on 12 Feb 2025
Edited: Samayochita
on 12 Feb 2025
Hi Dushan,
I see that you are trying to create a time-based x-axis starting from a specific date and time (like 2/6/2021 7:12 AM), having one-minute intervals. I suggest you try to implement the following:
- First, create a time range that spans from 2/6/2021 7:12 AM to 2/7/2021 1:31 PM with 1-minute intervals. You can use MATLAB’s “datetime” (https://www.mathworks.com/help/matlab/ref/datetime.html) function.
- Next, format the x-axis to show only the time part, not the full date.
- For labeling, you can choose every 6 hours on the x-axis. Use “xticks” (https://www.mathworks.com/help/matlab/ref/xticks.html) and “xticklabels” (https://www.mathworks.com/help/matlab/ref/xticklabels.html) to define custom ticks and labels for the x-axis.
Below is an example code I wrote for your reference:
% Define start and end date:
startDate = datetime(2021, 2, 6, 7, 12, 0);
endDate = datetime(2021, 2, 7, 13, 31, 0);
% Create a date range with 1-minute intervals
timeRange = startDate:minutes(1):endDate;
% Format the X-axis to show time only (without the full date)
datetick('x', 'HH:MM', 'keeplimits');
% Label the X-axis with 6-hour intervals
xticks(startDate:hours(6):endDate);
xticklabels(datestr(startDate:hours(6):endDate, 'HH:MM'));
Hope this helps!
Categories
Find more on Dates and Time 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!