sge
sge

Reputation: 7640

set Position in matlab results in unexpected position

I have the following matlab code snippet that generates two subplots aside each other.

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)]);

Since the legend is on top of the first subplot, i want to manually resize the second subplot so both have the same size. So i get the Position values and set them for subplot2 in the last line. Strangely, however, the subplot is shifted downwards a little so that the x-axis are not aligned.

This also occurs when i call

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

in direct succession.

Am i doing something wrong or is this a known issue?

Update:

Neither adding the drawnow; nor changing units to pixels changed anything. Attached an image that shows the issue.

Misaligned x axis

Upvotes: 3

Views: 161

Answers (1)

Daniel
Daniel

Reputation: 36710

Now I was able to reproduce your issue, it only happenes for very small figure sizes. Instead of resizing the second plot, draw a invisible legend on the right side. It will take exactly the same space the first legent takes:

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

And remove the last line from your code.

Upvotes: 1

Related Questions