我对 matlab 中两个轴的绘图如何调整大小感到困惑。我发现结果中存在不一致的行为,具体取决于我是否在调试器中单步执行图形生成代码(正常工作),或者是否一次运行全部代码。
例如,在以下函数中,我链接两个轴的 Position 属性:
- 如果我在最后一行放置一个断点,并单步执行它,第一个轴的位置会自动更改,因为它应该是
- 如果我一次运行它,它不会改变并且与第二个轴不对齐
这是什么原因?
如果这很重要的话,我正在使用 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
的变化,但您却显式更新 OuterPosition
。 OuterPosition
中所做的更改最终会返回到 Position
中的更改,但如果处理器或渲染器繁忙,则无法将更改传播回来(并通知监听器)直到处理器空闲。
要解决此问题,您可以使用 drawnow
显式告诉 MATLAB 在更改 OuterPosition
后立即刷新所有排队事件。 。这将导致 Position
更新并通知所有潜在的监听器,在您的情况下,这将导致 ax1
的 Position
被更新。
ax2.OuterPosition(4) = 1 - ax2.OuterPosition(1);
drawnow nocallbacks
使用调试器单步调试时看不到此行为的原因是,此时 MATLAB 解释器处于空闲状态,能够实时处理所有图形事件。
关于Matlab 轴在非交互模式下调整大小行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36033807/