Search code examples
matlabplotsubplothandlessave-as

Matlab save individual subplot as jpg


In a for loop, I create a variable number of subplots that are displayed on a single figure. Can I also save each subplot as a separate, full size plot and image file (preferably JPG)?


Solution

  • Use copyobj to a new figure and then use saveas with the new figure handle:

    Example code that YOU should have provided (see SSCCE):

    figure
    nLines = 2;
    nColumns = 3;
    handles = zeros(nLines,nColumns)
    for line = 1:nLines
      for column = 1:nColumns
        handles(line,column)=subplot(nLines,nColumns,column+(line-1)*nColumns);
        plot([line column]);
        title(sprintf('Cool title (%d,%d)',line,column))
        ylabel(sprintf('Ylabel yeah (%d,%d)',line,column))
        xlabel(sprintf('Xlabel nah (%d,%d)',line,column))
      end
    end
    

    Here I have the subplot handles saved, but supposing you don't have them saved:

    axesH = findobj(gcf,'Type','axes','-not','Tag','legend'); % This will change the order from which the axes will be saved. If you need to save in the correct order, you will need access to the subplot handles
    nAxes = numel(axesH)
    newFig = figure;
    for k=1:nAxes
       newAxes=copyobj(axesH(k),newFig);
       % Expand subplot to occupy the hole figure:
       set(newAxes,'OuterPosition',[0 0 1 1]);
       tightInset=get(newAxes,'TightInset');
       set(newAxes,'Position',[tightInset(1:2) [1 1]-(tightInset(3:4)+tightInset(1:2))])
       saveas(newFig,sprintf('axes_%d.jpg',k),'jpg');
       delete(newAxes);
    end
    delete(newFig);
    

    Example of one axes saved:

    One subplot example

    To remove the deadspace I used information available on this topic.