matlab

How to get handle of the legend of a plot generated through plotyy when importing a fig file?


I'd like to get the handle of the legend of the figure here so that I can copy the figure's legend entries when replotting the legend on a subplot.

If I try to find the axes by running findobj(ax1,'Type','axes','Tag','legend') though, it just returns an Empty matrix: 0-by-1. Is there another way to get the legend?


Solution

  • The setup is like this. First the figure is created. This one servs as a canvas. Then the other objects are drawn upon the figure. The objects drawn is called children. The function call,

    plot(0:10);
    

    Creates a figure and one child. The child is called an axes. By adding a legend with,

    legend('This is a legend');
    

    matlab creates an axes object named legend an places it in the figure. This becomes another child. The object handles to the children can be found in

     h = get(gcf,'Children')
    

    Then you may save the figure and close it down. When you are loading the figure again, the whole figure, with legends and so on is restored. This includes giving the children new object handles. This means that the children can again be retrieved with,

     h = get(gcf,'Children')
    

    you can find the child properties with

    get(h(anyElementInChButJustOnePerCall))
    

    By looking at the properties, you will notice that there is a porperty called Tag. This one is named legend for the legend. You can find it with get and look through the properties for all handles (should not be too many) or automatically with a for loop

    h = get(hFig,'children');
    hLeg = [];
    for k = 1:length(h)
        if strcmpi(get(h(k),'Tag'),'legend')
            hLeg = h(k);
            break;
        end
    end
    

    Where hFig is the handle of the figure (written in the upper right "Figure..."). Or if the figure is just loaded it can be accessed with "get current figure" gcf.