查明是否可以将日期时间 x 轴绘制到给定轴中

Find out if it is possible to plot a datetime xaxis into a given axis

我有一个 matlab 函数,可以在提供的轴 plotAxis 上绘制 (datetime, double) 系列。然而,如果 plotAxis 已经包含一个 (double, double) 系列,那么你会得到一个错误:

'Data inputs must match the axis configuration. A numeric axis must have numeric data inputs or data inputs which can be converted to double.'

我知道我可以查询 plotAxis.XAxis 并找出它是 DatetimeRuler 还是 NumericRuler。如果是前者,那我就去图谋,如果是后者,那我就优雅地失败吧。但是,似乎新轴的 XAxis 属性 的默认类型也是 NumericRuler ,在这种情况下,您可以在其上绘制 datetime (大概是因为没有绘制了其他现有 (double, double) 系列)。

有没有一种通用的方法,给定一个轴对象来确定是否可以在其上绘制 (datetime, double)(当然,try/catch 块除外)?

您描述它的方式(据我测试)尺子的 class 不是要查找的内容。对于不包含任何数据的新图,class 可以是 NumericRuler。然后,此标尺可以毫无问题地接受 datetime 数据。但是,当轴在水平轴上包含非 datetime 数据时,NumericRuler 将无法很好地处理其他数据类型并引发错误。因此,测试标尺类型不是可行的方法。

我建议测试轴的 XData 中已经包含的数据类型 Children:

ax = gca;
if all(cellfun(@(x) isempty(x) || isdatetime(x.XData), {ax.Children}))
    % Ok to plot datetime
else
    % Not ok to plot datetime, it will throw an error
end

这测试两个条件之一:

  1. 轴的Children是空的,即轴上没有图形。因此,可以绘制datetime个数据。
  2. 所有轴的 Children 都是 datetime 类型,因此可以绘制更多 datetime 数据。

cell 中使用 {ax.Children} 是因为轴的 Children 可能不适合一个常规数组,因为它们具有不同的类型或维度。