MATLAB: How to set the subplot position without worrying about the outside legends

legendsubplot

I have two subplots: han1 = subplot(1,2,1) and han2 = subplot(1,2,2). han1 has a legend with 4 rows, han2 has a legend with 2 rows. The position of their legends are both "southoutside". The problem I am having is that the "position" setting for both of these subplots considers the legends, so I am having a hard time aligning these two subplots (without worrying the legends). When I finally align them up, the distance between the legends and the subplots are different. What is a way to get around this?
Thanks!

Best Answer

One option would be to change the position of the larger post-legend axis after the legend has been added, to keep them aligned:
han1 = subplot(1,2,1);
h1 = plot(rand(10,2));
han2 = subplot(1,2,2);
h2 = plot(rand(10,4));
legend(h1, {'1','2'}, 'location', 'southoutside');
legend(h2, {'1','2','3','4'}, 'location', 'southoutside');
drawnow;
han1.Position = [han1.Position(1) han2.Position(2) han1.Position(3) han2.Position(4)];
Alternatively, you could try using my legendflex function, which allows you to place a lengend outside a subplot without resizing the subplot:
han1 = subplot(1,2,1);
h1 = plot(rand(10,2));
han2 = subplot(1,2,2);
h2 = plot(rand(10,4));
legendflex(h1, {'1','2'}, 'ref', han1, 'anchor', {'s','n'}, 'buffer', [0 -20]);
legendflex(h2, {'1','2','3','4'}, 'ref', han2, 'anchor', {'s','n'}, 'buffer', [0 -20], 'nrow', 2);
Related Question