Search code examples
matlabplotgraphicaxes

Get Number of plots on saved matlab figure automatically


Lets think we have a figure as;

figure(1),plot(1:10);hold on;plot(2:2:45)

and save this figure. When i open it as *.*fig format, i want to get information from figure(1) how many plots on it. There is 2 plots on figure1, but i would like to get this automatically.


Solution

  • You can use a command like

    numplots =  numel(get(gca,'Children'))
    

    or if you are looking for how many lines :

    numlines = numel(findobj(gcf,'Type','line'))
    

    for example a function that does this could be:

    function NumSons = sons_of_figure
    [filename,pathname]=uigetfile('*.fig','Select File to Open');
            if isequal(filename,0) || isequal(pathname,0)
                return
            else
                open(fullfile(pathname,filename));
                NumSons = numel(get(gca,'Children'));
            end
    end
    

    To change the color of a line you need to know (or find) its handle. In your example you can associate at each line a name:

    figure(1),plot(1:10,'DisplayName','one');hold on;plot(2:2:45,'DisplayName','two')
    

    Then you save and load the figure. If you want to change the color of the first line, named 'one', to red:

    line1 = findobj(gcf,'DisplayName','one')%line1 is the handle to the line you want
    set(line1,'color','r')