Clear Filters
Clear Filters

How to include more precise time intervals on my graph? (MATLAB R2020a)

17 views (last 30 days)
I have plotted a graph of time vs gauge height. So far, on the x axis of time, I only have time seperated by days, but I want it to be seperated by hours and even minutes. I was wondering how do I do this. I have tried this and it doesn't work. When I didn't include the month, day, hour, minute, and serial date lines, the graph's x axis was just filled with 00:00s but the spacing between the tickmarks was the same. Now, with all this code, I keep getting multiple error messages saying that my index numbers are outside the acceptable range of 16 for the hour and minute lines. I also have an error using the datenum function with incorrect number of arguments. I found these techiniques on the MATLAB help page, and I thought you have to create an array for the time intervals. But nothing is working.
I'm really confused and I don't know why it's so complicated to just plot the x axis by hour or minute time intervals.
t = datetime(col1, "InputFormat","yyyy-MM-dd HH:mm")
%col1 = Array(:, 1);
%col5 = Array(:, 5);
month= Array.datetime(6,7);
day= Array.datetime(30,07);
hour= Array.datetime(01,24);
minute= Array.datetime(01,59);
sdate = datenum(month,day,hour,minute);
plot(t, col2)
xlabel('Date and Time')
ylabel('Discharge, cubic feet per second')
dateFormat = 'HH:MM';
datetick('x', dateFormat,"keeplimits", "keepticks")

Answers (1)

jonas on 29 Aug 2020
Edited: jonas on 29 Aug 2020
Not so complicated, you just need to figure out the right properties to change. The function "datetick" is for datenum, which is inferior to the newer datetime class. Here's an example.
ax = axes;
t = datetime(2020,1,1):hours(1):datetime(2020,1,10);
y = rand(1,numel(t))
ax.XAxis.TickValues = t(1):hours(12):t(end); % change time ticks to 12 hour intervals
ax.XAxis.TickLabelFormat = 'HH:mm'; % change time format, note "mm"
ax.XAxis.TickLabelRotation = 45;


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!