how to subplot n figures (pcolor) using for loop (matlab)

Viewed 121

I have n saved fig files (all the figures are pcolor figure) and I want to plot all the figures in one new subplot (n X 2). Can anyone please help me out here? I will be really really grateful :)

    % Open each figure and copy content
    for i = 1:nFig
        % Open fig-i
        filename = fullfile(rep,list(i).name);
        fighand =  openfig(filename,'invisible');

            h=subplot(nFig,2,i);


        % Close fig-i
        close(fighand)
    end
1 Answers

You can use copyobj to copy the contents of an existing axes to a target axes. See comments for explanation:

N = 4;

%% generate some figs
fig = cell(1,N);

for k = 1:N
    fig{k} = figure(k);
    fig{k}.Name = sprintf('fig_%i', k);
    pcolor(rand(10));
    
    xlabel(sprintf('some xlabel %i',k))
    ylabel(sprintf('some ylabel %i',k))
    savefig(fig{k}, fig{k}.Name)
end


%% load figs and make nice subplot
fig_all = figure(99);clf;
for k = 1:N
    % load figure
    fig_tmp = openfig(sprintf('fig_%i', k),'invisible');
    % set fig_all as the current figure again
    figure(fig_all);
    % create target axes
    ax_target = subplot(N/2,2,k);
    pcolor(ax_target, rand(5)*0.001); cla; % plot some random pcolor stuff to setup axes correctly

    % get the source data and copy to target axes
    ax_src = fig_tmp.Children;
    copyobj(ax_src.Children, ax_target);
    % set axes properties of target to those of the source
    ax_target.XLim = ax_src.XLim;
    ax_target.YLim = ax_src.YLim;
    
    % copy the axes labels
    ax_target.XLabel.String = ax_src.XLabel.String;
    ax_target.YLabel.String = ax_src.YLabel.String;
end

enter image description here

Related