在MATLAB中先生成子图,然后将它们组合成一个图形

10

我的程序在命令循环期间生成小图形。是否有一种方法只保存这些图形,然后稍后将它们合并成一个图形?

4个回答

17

考虑下面的代码:

hFig = figure;

%# create temporary subplots as template
for i=1:2, h(i) = subplot(2,1,i); end       %# create subplots
pos = get(h, 'Position');                   %# record their positions
delete(h)                                   %# delete them

%# load the .fig files inside the new figure
fileNames = {'a.fig' 'b.fig'};              %# saved *.fig file names
for i=1:2
    %# load fig
    hFigFile = hgload( fileNames{i} );

    %# move/copy axis from old fig to new fig
    hAx = get(hFigFile, 'Child');           %# hAx = gca;
    set(hAx, 'Parent',hFig)
    %#hAx = copyobj(hAx,hFig);

    %# resize it to match subplot position
    set(hAx, 'Position',pos{i});

    %# delete old fig
    delete(hFigFile)
end

这是从新闻组讨论中改编而来的。


1
太棒了,真的非常好。非常感谢,这节省了很多痛苦。 - Vass
而且新闻组讨论的链接非常有用。 - Vass

1

我这里有一个例子作为答案:

h1 = figure(1)
plot(1:10,'o-r');
title('title');
xlabel('xlabel');
ylabel('ylabel');

% Copy contents
ch(1) = copyobj(gca,gcf);

% Figure 2
h2 = figure(2)
plot(1:30,'o-r');
title('title fig2');
xlabel('xlabel');
ylabel('ylabel');
% copy contents
ch(2) = copyobj(gca,gcf);

figure(3)
sh = subplot(1,2,1);
clear axes
p = get(sh,'position');
ah = copyobj(ch(1),gcf);
set(ah,'position',p);

% Create axis template
sh = subplot(1,2,2);
clear axes
p = get(sh,'position');
ah = copyobj(ch(2),gcf);
set(ah,'position',p);

% Delete template
% delete(sh);

1

Amro's solution非常有效,但对于箱线图,您需要重置Xtick和Xtick标签,否则,由于某种原因,它们将不会根据子图进行调整大小。在创建箱线图或打开图形后添加:

set(gca,'XTick',<1d vector>,'XTickLabel',<1d cell vector>)

或者自动添加刻度和标签。
set(gca,'XTickMode','auto','XTickLabelMode','auto')

有趣,谢谢分享。你试过复制轴而不是移动轴吗(在我的代码中被注释的那一行)?老实说,我的解决方案并不完美;例如,如果图形具有不同的颜色映射,则会失败(除非您采取额外的措施来解决这个问题)。 - Amro

1

使用 saveas。将子图保存为FIG文件,以便以后完全控制它(与JPG不同)。

选择平铺模式,然后使用 subplot 在一个图中显示多个图像。


那么,您如何将它们加载到单个图形中呢? - Vass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接