0
votes

How can I get MATLAB to display the dates and times on the x-axis of a plot?

I am trying to make a plot that shows the water level (WL) in cm over time, as illustrated in the image:

Water level over time. indices on x-axis, water level on y-axis

Right now, the x-axis of my plot just shows indices, but I want it to display the dates and times in the order: year, month, day, hour, minute. The format is not that important as long as it's readable and in that order. I also want to be able to control the ticks, so that the user won't be overwhelmed.

In MATLAB, I've been working with dates in the following way:

  1. An array that contains the DATES in yyyyMMddhhmm format as numbers.
  2. Multiple arrays that contain yyyy, MM, dd and so on.

WL and my DATES array have the same length, and they arranged so that WL(i) corresponds to DATES(i). Right now, my code looks like this:

figure(1)
hold on
plot(WL)
xlabel('Date')
ylabel('WL [cm]')
2
If you only provide one vector to plot then it can obviously only possibly know to plot it by index. Pass it two arguments. See: Plot Dates and Durations - excaza

2 Answers

0
votes

Assuming your WL and DATES looks like this:

WL = [6 4 5];
DATES = [201412241842
    201412251830
    201412261921];

You can do the following to convert DATES to datetime format:

dates = datetime(num2str(DATES),'InputFormat','yyyyMMddHHmm');

And then you just plot it:

plot(dates,WL)

enter image description here

0
votes

You could do this in two steps:

1) convert your date/time values to datenums

2) use datetick to make your x-axis the way you want