MATLAB: How to place a legend in best corner

bestlegendMATLAB

Is there a way to place legend in the best corner of subplot. I do not like it when the legend is in middle of whitespace.

Best Answer

Give this a try as a first cut...written for a one-line plot as is and takes the legend, axis handles.
Generalized, it could handle simply a figure handle and find the axes and legend from it and retrieve all the X,YData.
But, illustrates the logic idea of above; seemed to work here for a test case where drew the legend on a line and then moved the legend to not clash, but that's the extent of testing.
function flag=legendclash(hAx,hLg,x,y)
% Returns T if data in line x,y cross legend box in axes hAx
AxPosn=hAx.Position; % get axis position vector
Axbot=AxPosn(2); Axtop=Axbot+AxPosn(4); % compute bounding box
Axlft=AxPosn(1); Axrgt=Axlft+AxPosn(3); % dimensions for axis
LgPosn=hLg.Position; % and same for the legend
LGbot=LgPosn(2); LGtop=LGbot+LgPosn(4);
LGlft=LgPosn(1); LGrgt=LGlft+LgPosn(3);
if strfind(hAx.YDir,'normal')
yscaled=interp1(hAx.YLim,[Axbot Axtop],y); % compute scaled plotted values

else
yscaled=interp1(hAx.YLim,[Axtop Axbot],y); % compute scaled plotted values
end
if strfind(hAx.XDir,'normal')
xscaled=interp1(hAx.xlim,[Axlft Axrgt],x); % in the axis bounding box

else
xscaled=interp1(hAx.xlim,[Axrgt Axlft],x); % in the axis bounding box
end
% test if data intersects inside the legend bounding box
flag=any(iswithin(yscaled(:),LGbot,LGtop) & iswithin(xscaled(:),LGlft,LGrgt));
end
iswithin is my oft-used utlity function that is just "syntax sugar" but makes for simpler high-level code...
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
NOTA BENE: ERRATUM
Corrected swapped indices in axis position calculation and inserted missing function keyword
ADDENDUM
Added logic to handle reversed axes