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)?
Asked
Active
Viewed 5,742 times
3

Simon Adcock
- 3,554
- 3
- 25
- 41

user1502755
- 51
- 1
- 4
2 Answers
2
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:
To remove the deadspace I used information available on this topic.
-
Thanks Warner. I end up with a separate file for subplot and colourmaps. I gave you the green tick for showing me how to enumerate the objects on a figure. I'll keep looking into it. – user1502755 Sep 30 '13 at 04:57
-
@user1502755 I couldn't get what is the issue with the subplot and colormap. If you provide a SSCCE from the subplots you're using and how to reproduce the issue you're getting I may be able to help you. – Werner Sep 30 '13 at 05:50
1
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.

chappjc
- 30,359
- 6
- 75
- 132
-
Thanks chappjc. It does as advertised, unfortunately my frames return empty colormaps. I'll keep looking into it. I gave you a useful click. – user1502755 Sep 30 '13 at 04:54
-