how to place a legend in best corner?
Show older comments
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.
Accepted Answer
More Answers (1)
dpb
on 6 Mar 2019
Try
legend(___,'Location','best')
ML tries to avoid the most data it can if it can find a location that the legend doesn't occlude anything.
It generally is "ok", but may not be what one might choose visually; the logic certainly isn't perfect.
Other than that, it's "pick a spot and go!" in that all other named choices are fixed locations relative to the axes or you set the actual position yourself programmatically (and then the "best" logic reverts to your own devices so you can test your skills against those of TMW :) )..
2 Comments
meghannmarie
on 6 Mar 2019
Edited: meghannmarie
on 6 Mar 2019
dpb
on 6 Mar 2019
I know of no builtin functionality, sorry.
Best I can think of is that you can retrieve the position of the legend where you choose to put it. Those are, by default, normalized dimensions within the axes object.
Then you would have to scale the plotted data to the same set of normalized position values of the axis and check if there is an intersection of values of the x,y normalized data within that area of the legend.
I have meetings in town here shortly so don't have time to try to see if can think of just what such code would look like at the moment, but I think that's the general idea.
I don't know if you can see the internals of the legend function any more or not; seems like TMW has made it almost totally opaque now so you may not be able to go look at what code for collision avoidance is inside it any longer.
Probably at least worth of a look to see if you can find anything on the FEX that somebody else may have already done...
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!