Legend Location 'Best', but still in corner if possible

I want to set the Location of my legend to 'Best' (like `legend('y1','y2','Location','Best')`) so the legend doesn't collide with my lines, but at the same time, I would prefer to have it in a corner if that's possible with no data collision. Is there a way of implementing this?

In case anyone's interested in this, I wrote a function based on @S.. answer that does, what I wanted to achieve. Here's the code:

``````function setPositionCornerBest( figureHandle )
%Sets the Location of the legend of the figure that is referenced by figureHandle to one of the Corners if there is no data in the Corners. Otherwise it sets it to 'Best'
h = figureHandle;

figObjects = get(h,'Children');
legHandle = findobj(figObjects,'Tag','legend');
axHandle = findobj(figObjects,'Type','axes','-and','Tag','');
lineHandle = findobj(figObjects,'Type','line','-and','Parent',axHandle);
axPos = get(axHandle,'Position');

LimX = get(axHandle,'XLim');
LimY = get(axHandle,'YLim');

xScaling = (LimX(2)-LimX(1))/axPos(3);
yScaling = (LimY(2)-LimY(1))/axPos(4);

locCell = {'NorthWest','NorthEast','SouthEast','SouthWest'};
ii = 1;
interSecFlag = true;

while (interSecFlag) && (ii<=4)
set(legHandle,'Location',locCell{ii});
legPos = get(legHandle,'Position');

x(1) = LimX(1)+(legPos(1)-axPos(1))*xScaling;
x(2) = x(1);
x(3) = LimX(1)+(legPos(1)+legPos(3)-axPos(1))*xScaling;
x(4) = x(3);
x(5) = x(1);

y(1) = LimY(1)+(legPos(2)-axPos(2))*yScaling;
y(2) = LimY(1)+(legPos(2)+legPos(4)-axPos(2))*yScaling;
y(3) = y(2);
y(4) = y(1);
y(5) = y(1);

for jj = 1:numel(lineHandle)
xline = get(lineHandle(jj),'XData');
yline = get(lineHandle(jj),'YData');
[xInter ~] = intersections(x,y,xline,yline);
if numel(xInter) == 0
xInterFlag(jj) = 0;
else
xInterFlag(jj) = 1;
end
end

if all(xInterFlag==0)
interSecFlag = false;
end

ii = ii + 1;
end

if interSecFlag
set(legHandle,'Location','Best');
end

end
``````
• That a shiny and useful piece of code right there! – Adriaan Jan 20 '16 at 9:15
• Trick question: does it also work for logarithmic plots? – Andras Deak Jan 20 '16 at 12:43
• @AndrasDeak If the answer is 'no', I don't see the trick in that question :D – Max Jan 20 '16 at 13:02
• OK, it may have been just a rhetorical question;) As in: I didn't try. – Andras Deak Jan 20 '16 at 13:06
• Your script it's great. Very useful for me. However, I should report a small bug which occurs when the plot limits re not the default ones (when they do not coincide with the data lenght) It is neacessary to correct the expressions 'x(1), x(3)', 'y(1)', 'y(3)' to taking that into account. It becomes as follows: x(1) = LimX(1)+(legPos(1)-axPos(1))*xScaling; x(3) = LimX(1)+(legPos(1)+legPos(3)-axPos(1))*xScaling; y(1) = LimY(1)+(legPos(2)-axPos(2))*yScaling; y(2) = LimY(1)+(legPos(2)+legPos(4)-axPos(2))*yScaling; – Justino Rodrigues Feb 23 '17 at 15:52

I don't have a complete answer, only a sketch. However, you could try to first set the legend in a corner

``````a=legend('y1', 'y2', 'Location', 'NorthEast')
``````

and then obtain its position

``````get(a,'Position')
``````

You can convert this position to coordinates and simply test whether your lines cross any border of the legend using http://www.mathworks.com/matlabcentral/fileexchange/11837-fast-and-robust-curve-intersections .If this is the case, try another corner, until there is no corner left. In that case, use 'Best'.

• sounds good. I'll try this and let you know if it worked asap. It might take a few days though. So far thanks for your efforts! – Max Jan 7 '16 at 10:01
• wait, how do I even transform the Position of the legend into a curve in the coordinates of my plot? – Max Jan 7 '16 at 14:14
• it is a bit annoying to do, but you can get the position of the axis (x and y axis), and you also know their range. So you can use this to convert any position in coordinates. I agree that the solution is quite ugly, but it might work – S.. Jan 7 '16 at 15:19
{"ft_lang_label":"__label__en","ft_lang_prob":0.80050963,"math_prob":0.9612401,"size":3912,"snap":"2019-26-2019-30","text_gpt3_token_len":1237,"char_repetition_ratio":0.116171956,"word_repetition_ratio":0.05102041,"special_character_ratio":0.32592025,"punctuation_ratio":0.15995261,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9878562,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-06-18T08:14:35Z\",\"WARC-Record-ID\":\"<urn:uuid:d380c259-5bd9-4dba-a953-6a76967e04ff>\",\"Content-Length\":\"129267\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:55ae946d-7c75-4a8c-8ee6-432cddfc3234>\",\"WARC-Concurrent-To\":\"<urn:uuid:7c7184d6-c688-4a77-8985-c5dfd50fb765>\",\"WARC-IP-Address\":\"151.101.1.69\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/34593695/legend-location-best-but-still-in-corner-if-possible/34895794\",\"WARC-Payload-Digest\":\"sha1:KFIINKIMDKQ6VEC2OUNSQ4FLUQ4VGZGE\",\"WARC-Block-Digest\":\"sha1:4VXLXRD5CA4HMLBLU4J3AW6TLLSFYVGX\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-26/CC-MAIN-2019-26_segments_1560627998690.87_warc_CC-MAIN-20190618063322-20190618085322-00104.warc.gz\"}"}