Kri*_*ish 5 matlab plot contour matlab-figure
我想知道如何绘制在z轴上间隔开的多个2D等高线图,在这样的3D图中:

注意:这个答案的第一部分是针对HG1图形的.如果您正在使用MATLAB R2014b及更高版本(HG2),请参阅第二部分.
该contour函数在内部创建了许多patch对象,并将它们作为组合的hggroup对象返回.因此,我们可以ZData通过将Z维度移动到所需的水平来设置所有补丁(默认情况下,轮廓显示在z = 0).
这是一个例子:
[X,Y,Z] = peaks;
surf(X, Y, Z), hold on % plot surface
[~,h] = contour(X,Y,Z,20); % plot contour at the bottom
set_contour_z_level(h, -9)
[~,h] = contour(X,Y,Z,20); % plot contour at the top
set_contour_z_level(h, +9)
hold off
view(3); axis vis3d; grid on
Run Code Online (Sandbox Code Playgroud)

以下是set_contour_z_level上面使用的函数的代码:
function set_contour_z_level(h, zlevel)
% check that we got the correct kind of graphics handle
assert(isa(handle(h), 'specgraph.contourgroup'), ...
'Expecting a handle returned by contour/contour3');
assert(isscalar(zlevel));
% handle encapsulates a bunch of child patch objects
% with ZData set to empty matrix
hh = get(h, 'Children');
for i=1:numel(hh)
ZData = get(hh(i), 'XData'); % get matrix shape
ZData(:) = zlevel; % fill it with constant Z value
set(hh(i), 'ZData',ZData); % update patch
end
end
Run Code Online (Sandbox Code Playgroud)
从R2014b开始,上述解决方案不再起作用.在HG2中,轮廓对象不再具有任何图形对象作为子对象(为什么某些对象的子属性为空?).
幸运的是,有一个简单的修复,具有被称为轮廓的隐藏属性ContourZLevel.您可以在此处和此处了解更多未记录的轮廓图自定义.
所以前面的例子变成了:
[X,Y,Z] = peaks;
surf(X, Y, Z), hold on % plot surface
[~,h] = contour(X,Y,Z,20); % plot contour at the bottom
h.ContourZLevel = -9;
[~,h] = contour(X,Y,Z,20); % plot contour at the top
h.ContourZLevel = +9;
hold off
view(3); axis vis3d; grid on
Run Code Online (Sandbox Code Playgroud)

在所有版本中都适用的另一种解决方案是将轮廓"父"到hgtransform对象,并使用简单的z平移对其进行转换.像这样的东西:
t = hgtransform('Parent',gca);
[~,h] = contour(X,Y,Z,20, 'Parent',t);
set(t, 'Matrix',makehgtform('translate',[0 0 9]));
Run Code Online (Sandbox Code Playgroud)