在非交互模式下调整 Matlab 轴大小的行为异常

Matlab axes resize in non interactive mode behaves unexpectedly

我对在 matlab 中如何调整具有两个轴的图的大小感到困惑。我在结果中发现了不一致的行为,这取决于我是在调试器中单步执行图形生成代码(正常工作),还是 运行 一次全部完成。

例如,在下面的函数中,我链接了我的两个轴的位置 属性:

这是什么原因?

如果这很重要,我正在使用 2015B。

function graph_test

% set up a horizontal bar plot with a scattre plot on a secondary x-axis
% at the top
barh(1:10)
ax1 = gca;
set(ax1,'Box','off');
ax2 = axes('XAxisLocation','top','Color','none','Position', ax1.Position);
linkaxes([ax1 ax2],'y'); 
linkprop([ax1 ax2],'Position');  
set(ax2,'Ytick',[]);
hold on;
scatter(ax2,[1:-.1:.1],[1:10]);
xlabel(ax1,'bottom axis');
xlabel(ax2,'top axis');


% set title
% we need to set this on second axis so that it does
% not overlap with axis legend
% the secondary axis is not auto resized as per matlab docs

title(ax2,'My graph');

% resize ax2 manually
ax2.OuterPosition(4) = 1-ax2.OuterPosition(1);

end

问题是您正在监听 Position 中的更改,但您正在明确更新 OuterPositionOuterPosition 中所做的更改最终会返回到 Position 中的更改,但如果处理器或渲染器很忙,则在处理器空闲之前无法传播更改(并通知侦听器)。

要解决此问题,您可以明确告诉 MATLAB 在使用 drawnow 更改 OuterPosition 后立即刷新所有排队的事件。这将导致 Position 更新并通知所有潜在的听众,在您的情况下,这将导致更新 ax1Position

ax2.OuterPosition(4) = 1 - ax2.OuterPosition(1);
drawnow nocallbacks

您在使用调试器逐步执行时看不到此行为的原因是,在那个时间点,MATLAB 解释器处于空闲状态并且能够实时处理所有图形事件。