MATLAB: How to check if a figure has z-axis data

figure propertieszlim

How can I check the number of dimensions of a figure? I want to be able to set custom limits of each axis, supporting both 2D and 3D plots. Of course if I attempt to set zlim for a 2D plot, I get an error.
I thought about counting the number of axis, but I don't think this will work, since other things, such as colorbars, are also condidered axes.

Best Answer

My tests show that all axes of type numeric and datetime have ZLim that can be queried, so the presense of ZLim cannot be used to distinguish 2D from 3D. The only way I could think of to reliably distinguish a 2D axes from a 3D axes was to look for 3D objects inside the axes.
Polar axes and geoaxes do not have a ZLim, so I deem them to be 2D.
One thing I did not do is look for hgtransform groups: a purely 2D object such as an image can be rotated or translated into Z without there being any object that has explicit Z coordinates. One could potentially examine the Matrix property of an hgtransform object to determine whether it could move anything into 3D.
Note here that the ability to (generally) set ZLim does not mean that you can set it to any particular datatype without checking: you cannot set a Datetime Z Ruler to numeric zlim for example.
fig = gcf;
all_zobj = findobj(fig, '-property','ZData');
all_ax = findobj(fig, 'type', 'axes');
all_other_ax = findobj(fig, 'type', 'polaraxes', '-or', 'type', 'geoaxes');
all_zd = get(all_zobj, 'ZData');
if ~iscell(all_zd); all_zd = {all_zd}; end %no objects or 1 object case.
no_z = cellfun(@isempty, all_zd);
obj_3d = all_zobj(~no_z);
ax_3d = ancestor(obj_3d, 'axes');
if ~iscell(ax_3d); ax_3d = {ax_3d}; end
all_unique_ax3d = unique( [ax_3d{:}] );
all_unique_ax2d = setdiff( [all_ax, all_other_ax], all_unique_ax3d );