Why does Tiledlayout return error when using a figure with datetime as x-axis?

Hello,
I am trying to use tiledlayout to display several figures. The figures use numbers (double) on the y-axis and dates (datetime) on the x-axis. When I run my code, I recieve the following error (repeated four times).
"Warning: Error updating Line.
Conversion to double from datetime is not possible."
Matlab displays the figure I opened in a seperate window; however, the tiltedlayout figure displays an empty figure
The code I am running is posted below:
open([pwd '\ClusterData\SlopeFigs\m10d30rSlp.fig']);
gh1 = gca;
figure (88)
t = tiledlayout(2,2);
nexttile
copyobj(gh1.Children,gca)
I tried an example figure from MATLAB with number on both axes and it works fine. Therefore, I believe the issue is related to datetime values not being supported in tiledlayout. Can anyone confirm?
Thanks,
Allon

 采纳的回答

datetime x-axis is supported in tiledlayout. Here's an example:
x = datetime(2024,9,3):hours(1):datetime(2024,9,5);
y = rand(size(x));
figure
tiledlayout(2,2)
nexttile
plot(x,y)
gh1 = gca; % go ahead and store the axes handle
The problem is trying to copy objects from an axes whose XAxis is a DatetimeRuler to an axes whose XAxis is a NumericRuler (which the new axes's XAxis is by default). This is reproducing the problem:
figure
t = tiledlayout(2,2);
nexttile
copyobj(gh1.Children,gca)
Warning: Error updating Line.

Conversion to double from datetime is not possible.
A workaround is to plot something with datetime x-values in the new axes first (making that XAxis a DatetimeRuler), then copy the stuff, then delete what you plotted first. Example:
figure
t = tiledlayout(2,2);
nexttile
line_to_delete = plot(datetime(0,0,0),NaN);
copyobj(gh1.Children,gca)
delete(line_to_delete)
There may be a better solution, but this seems to work ok.

3 个评论

Another possible workaround is to copy the entire axes (including its Children) to the tiledlayout, rather than copying the old axes Children to the new axes.
Here I'll copy the same axes twice into a tiledlayout, in order to show how to control the position of the new axes in the tiledlayout:
x = datetime(2024,9,3):hours(1):datetime(2024,9,5);
y = rand(size(x));
% original figure
figure
plot(x,y);
gh1 = gca;
% new figure with tiledlayout
figure
t = tiledlayout(2,2);
new_ax = copyobj(gh1,t);
new_ax.Layout.Tile = 1;
new_ax = copyobj(gh1,t);
new_ax.Layout.Tile = 2;
Voss,
Thank you this was exactly what I needed! Your second comment was very helpful in pointing me to the correct solution. Much appreciated.
-Allon

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Axes Appearance 的更多信息

产品

版本

R2024a

标签

Community Treasure Hunt

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

Start Hunting!

Translated by