Frage

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)?

War es hilfreich?

Lösung

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.

Andere Tipps

Say you have the handle to the subfigure's axis, ha, you can use getframe and frame2im as follows,

F = getframe(ha);
[im,map] = frame2im(F);
if isempty(map)
    imwrite(im,'subframe.jpg');
else
    imwrite(im,map,'subframe.jpg');
end

Note that this will save the axis exactly how it appears on your screen, so resize the figure to your liking before saving. To use as much figure real estate as possible, tryout the subfigure_tight function on MATLAB Central.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top