pre-set axis limit to datetime

Hi:
I have a figure and I want to set the x-axis to 'datetime' type before add any plot there, below is the code:
figure
ax=gca;
ax.XLim=[datetime('now'),datetime('now')+day(1)]
Matlab reported error like below:
Value must be a 1x2 vector of numeric type in which the second element is greater than the first element or is Inf.
however, the code below works:
figure
ax=gca;
ax.XLim=[1,2]
and the code below works:
ax=gca;
ax.XLim=[1,2]
figure
plot([datetime('now'),datetime('now')+day(1)],[1,1])
so, it seems like the Matlab do not accept set the x-axis to datetime if no 'datetime' type plot added to the figure.
is there anyway can address this issue?
Thanks!
Yu

 Accepted Answer

The axis ruler can be set directly to a DatetimeRuler.
ax = axes;
ax.XAxis = matlab.graphics.axis.decorator.DatetimeRuler;
ax.XLim = [datetime(2020,1,1) datetime(2020,1,2)];

4 Comments

Hi:
Your sample code works fine, the problem is that, if I set the time zone for the datetime, Matlab report error. Below is the sample code:
figure
ax=gca;
ax.XAxis = matlab.graphics.axis.decorator.DatetimeRuler;
ax.XLim = [datetime('now','TimeZone', 'America/New_York'),datetime('now','TimeZone', 'America/New_York')+day(2)]
do you have any further suggestions?
Thanks!
Good catch. In this case, it would be simpler to call plot with dummy data and then clear the axes.
xLimits = [datetime('now','TimeZone', 'America/New_York') datetime('now','TimeZone', 'America/New_York')+day(2)];
yLimits = [0 1];
ax = gca;
plot(ax, xLimits, yLimits);
cla(ax); % clear axes
ax.XLim = xLimits;
ax.YLim = yLimits;
figure
ax=gca;
ax.XAxis = matlab.graphics.axis.decorator.DatetimeRuler;
plot(ax,[datetime('now','TimeZone', 'America/New_York'),datetime('now','TimeZone', 'America/New_York')+day(2)])
cla(ax)
ax.XLim = [datetime('now','TimeZone', 'America/New_York'),datetime('now','TimeZone', 'America/New_York')+day(2)]
Value must be a 1x2 vector of numeric type in which the second element is greater than the first element or is Inf.
ax.YLim = [ 0 1]
if cla(ax) is used as told, it still produces the same error
If you don't want a visible line on your axes you could plot using NaN as the Y data.
N = datetime('now','TimeZone', 'America/New_York');
plot(N, NaN);
xlim([N, N+days(2)])
ylim([0 1]);

Sign in to comment.

More Answers (0)

Categories

Asked:

on 22 Feb 2022

Commented:

on 19 Feb 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!