Search code examples
matlabdatetimeplot

Matlab plot with AM/PM in xtickformat but without day of year annotation


I'm working with Matlab 2023a. I'm trying to get Matlab to display a plot with the horizontal axis having hours, minutes, and AM/PM, but without any day, month, or year.

E.g. with mm = 0:minutes(5):hours(24); d = datetime() + mm, then

plot (d, randn(size(d)))
xtickformat ('hh:mm a')

displays the horizontal axis with 12:00 PM, 06:00 PM, 12:00 AM, 06:00 AM, etc. which is terrific. However, it also displays May 14, 2024-May 15, 2024 below the horizontal axis.

I don't want the day, month, and year annotation which is appearing under the horizontal axis. How can I tell Matlab not to display that?

I tried plotting with duration values instead of datetime, but then I can't get the AM/PM to appear. If someone knows how to display AM/PM with duration values, I would be interested to hear about that too.


Solution

  • A workaround is to query the xticks of the axes and from that build new xticklabels with the desired format, using char (or datestr, but that is now discouraged).

    So, run the following once the plot has been generated:

    xt = xticks;
    % xtl = datestr(xt(:), 'HH:MM PM'); % Discouraged. '(:)' needed in case xtl is 1×6
    xtl = char(xt, 'hh:mm a');
    xticklabels(xtl)