I know how to use the 'Location' input of the legend function, but none of the options put the legend right in the corner, they all leave a small space between the legend and the border of the plots. I've seen that it's possible to specify the location with a vector but I did not understand how to do it. Any help is appreciated.
1 Answer
Static approach
Here's a way to do it. I'm using the NorthEast
legend location as an example. For other positions you can use a similar logic (see below).
plot([2 -2]) % example plot...
le = legend('abc', 'Location', 'northeast'); % ... with legend
pos_le = get(le, 'position');
pos_ax = get(gca, 'position');
set(le, 'position', [pos_le(1) pos_le(2) pos_ax(1)+pos_ax(3)-pos_le(1) pos_ax(2)+pos_ax(4)-pos_le(2)]); % new position
To understand how this works, note that position properties are defined as
[lower_pos, left_pos, width, height]
So in this case the legend width is set to axis left position plus axis width minus legend left position; and similarly for the legend height. This logic works for a legend in the NorthEast
location. For other locations the modification should be obvious.
Dynamic approach
A drawback of the above is that the legend will cease to be aligned if the figure is resized. To keep it aligned as figure size changes, you can use the figure's SizeChangedFcn
property to specify code that is automatically executed when the figure is resized (ResizeFcn
also works, but it's not recommended).
plot([2 -2]) % example plot...
le = legend('abc', 'Location', 'northeast'); % ... with legend
set(gcf, 'SizeChangedFcn', 'le = findobj(gcf, ''type'', ''legend''); pos_le = get(le, ''position''); pos_ax = get(gca, ''position''); set(le, ''position'', [pos_le(1) pos_le(2) pos_ax(1)+pos_ax(3)-pos_le(1) pos_ax(2)+pos_ax(4)-pos_le(2)]);')
set(gcf, 'position', get(gcf, 'position')-1e-3) % force initial call to SizeChangedFcn
set(gcf, 'position', get(gcf, 'position')+1e-3) % restore initial position
Example: