在 matlab 中设置位置导致意外位置

set Position in matlab results in unexpected position

我有以下 matlab 代码片段,它生成两个彼此并排的子图。

h = figure;
sp1 = subplot(1,2,1); hold on;
plot(xenDates, yXenDates, '.', 'color', cmap(1,:));
plot(xenPatchDates, yXenPatchDates, '.', 'color', cmap(2,:));
xlabel('Time in Months');
ylabel('Cumulative Number');
legend('Vulnerabilities','Patches','Location','northoutside');
sp1Pos = get(sp1, 'Position');
sp2 = subplot(1,2,2); hold on;
sp2Pos = get(sp2, 'Position');
plot(kvmDates, yKvmDates, '.', 'color', cmap(1,:), 'Markersize', 10);
plot(kvmPatchDates, yKvmPatchDates, '.', 'color', cmap(2,:));
xlabel('Time in Months');
ylabel('Cumulative Number');
set(sp2, 'Position', [sp2Pos(1) sp1Pos(2) sp2Pos(3) sp1Pos(4)]);

由于图例位于第一个子图之上,我想手动调整第二个子图的大小,使它们具有相同的大小。所以我得到位置值并在最后一行为 subplot2 设置它们。然而,奇怪的是,子图向下移动了一点,以至于 x 轴没有对齐。

我打电话时也会出现这种情况

pos = get(sp2, 'Position');
set(sp2, pos(1) pos(2) pos(3) pos(4));

直接连续。

我是做错了什么还是这是一个已知问题?

更新:

既不添加drawnow;将单位更改为像素也没有改变任何东西。附上显示问题的图片。

现在我能够重现您的问题,它只发生在非常小的图形尺寸上。不要调整第二个图的大小,而是在右侧绘制一个看不见的图例。第一个图例需要的 space 完全相同:

h2=legend('Vulnerabilities','Patches','Location','northoutside');
set(h2,'visible','off')

并从您的代码中删除最后一行。