Clear Filters
Clear Filters

Can you convert DatetimeRuler to DurationRuler?

16 views (last 30 days)
Rohan Kadambi
Rohan Kadambi about 6 hours ago
Answered: Star Strider about 5 hours ago
I have a series of utilities that generate figures like:
fh = figure;
ax = axes(fh);
plot(ax, datetime("now")+minutes(1:5), 1:5, "--x");
Which use datetime objects for the XData (and therefore have a DatetimeRuler for the x-axis) because it makes it easier to find reference data in the future.
However, for presentations, I generally want plots that use a DurationRuler for the sake of clarity. Is there any way to update ax.XAxis (or maybe even all of the ax.Children entries) such that I could have figures that look like they were generated like this instead:
fh = figure;
ax = axes(fh);
plot(ax, minutes(1:5), 1:5, "--x");
I could update all the plotting utilities to optionally use Duration objects from some reference but this would effect several utilities and it would be more convenient to just pass an axis or figure handle to some function that could do the conversion after the figure exists.

Answers (2)

dpb
dpb 4 minutes ago
Unfortunately, something like
xl=ax.XLim; % retrieve current limits
xl(1)=dateshift(xl(1),"start",'minute'); % round down for first
xl(2)=dateshift(xl(2),"end",'hour'); % up for second
xl1=xl-xl(1) % convert to duration extent
ax.XLim=xl1; % redefine axes as duration
doesn't work; I've submitted enhancement request for the feature previously but so far, no joy.
I have found no way to force one into becoming the other; one has to redraw the graphic to make the change.
Probably the most direct way in your case would be to write a translation routine that does something like the above from the existing figure and then redraws it rather than fixing all the pieces individually, at least as a start.

Star Strider
Star Strider 2 minutes ago
I am not certain what you want or what your constraints are.
One option would be to do it in each figure or axes —
fh = figure;
ax = axes(fh);
x = datetime("now")+minutes(1:5);
y = 1:5;
figure
plot(ax, x, y, "--x");
figure
plot(ax, x-x(1), y, "--x");
figure
plot(ax, x-x(1), y, "--x");
ax.XAxis.TickLabelFormat = 'm';
This will convert the x-axis (in this instance) to a duration object in each figure without affecting whatever ‘x’ is generally.
.

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!