Very nice - thanks!
I wonder if anyone knows how to go a step beyond. That is, my legends are often like tables which I currently hand make as figures within figures. The table-like legend has row and column headings with only the symbols/line types in the cells instead of a label for every symbol/line. This is because the symbol itself might change to represent one variable and whether it's filled or open might represent another so it's identity is a combination of the row and column headings in the table.
You're right, this function relies on the current convention of graphics handles being numeric... I'll update it if and when HG2 is officially released (and perhaps by then legends will be flexible enough that this function won't be needed anymore).
This is what I was looking for, but I had to fix it to work well for axes embedded in complicated layouts involving uipanels, uitabs, etc. I use the excellent GUI Layout Toolbox from here on the file exchange to have lots of resizeable panels for example.
The problem is that this function assumes the legend should be placed relative to the figure. Unfortunately if a nested uipanel is used as a reference, the getpos() function does not correctly return the figure coordinates relative to the anchor. To get the global figure coordinates for a nested object, the GUI's hierarchy must be traversed, and the left and bottom coordinates summed for each parent up to the figure level. Each control's position is relative to it's parent, not to the figure.
Fortunately there's a simpler solution. I made the legend a child of the 'ref' object and fixed anywhere that temporary axes were made to the figure to be to the ref object instead. I also added a check that if this parent object is an axes, to get it's parent since the legend axes can't be a child of another axes. Finally, in the case of a plot in a densely nested GUI, the resize function should be on the parent component, not on the entire figure. This way when I drag the boundaries between uipanels to resize them, the legend and axes resize with them. I'm still experimenting with it, but this seems to solve my problems thus far.
I'll wait on permission to post my code since the author listed a copyright in the source.
Indeed, this function allows for flexible positioning of legend data without auto-resizing of your plot axes.
And as a bonus it is a great way to make a static legend-- as workaround for the often discussed problems of slow graphics performance when updating dynamic plot data with the base legend() command.