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)
AxPosn=hAx.Position;
Axbot=AxPosn(2); Axtop=Axbot+AxPosn(4);
Axlft=AxPosn(1); Axrgt=Axlft+AxPosn(3);
LgPosn=hLg.Position;
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);
else
yscaled=interp1(hAx.YLim,[Axtop Axbot],y);
end
if strfind(hAx.XDir,'normal')
xscaled=interp1(hAx.xlim,[Axlft Axrgt],x);
else
xscaled=interp1(hAx.xlim,[Axrgt Axlft],x);
end
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)
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
Best Answer