Reputation: 517
Let's say I have two figures stored in separate files A.fig
and B.fig
which contain two separate plots. Is there a way to load A.fig
and then do something like hold on
and then load B.fig
in the figure created for A.fig
so that I have both plots in the same axes?
Upvotes: 4
Views: 942
Reputation: 13963
I think the question is not really a duplicate of this one. The OP does not ask for a way to extract the data but for a way to combine the two stored figures. Admittedly, he could extract the data and plot it again. But there is a more elegant solution...
The actual plots are children of axes
which is a child of figure
. Therefore you can achieve what you want by copying the children of the second axes
into the first axes
with copyobj
. Before that, load the figures with openfig
. This method has the advantage to copy different types of 'plots' (line
, area
, ...).
The code to copy from B.fig
to A.fig
is as follows and works starting from R2014b:
fig1 = openfig('A');
fig2 = openfig('B', 'invisible');
copyobj(fig2.Children.Children, fig1.Children);
If you have a Matlab version prior to R2014b, you need to use the set
and get
functions since you cannot use .
-notation. More information can be found here. You can either use gca
to get the current axes after loading the figure like this:
fig1 = openfig('A');
ax1 = gca;
fig2 = openfig('B', 'invisible');
ax2 = gca;
copyobj(get(ax2,'children'), ax1);
... or get
them manually from the figure
-handle like this:
fig1 = openfig('A');
fig2 = openfig('B', 'invisible');
copyobj(get(get(fig2,'children'),'children'), get(fig1,'children'));
The following script creates two figures and then applies the above code to combine them.
If you are have Matlab version R2013b or higher, replace hgsave
with savefig
as suggested in the documentation.
%% create two figure files
x = linspace(0,2*pi,100);
figure; hold on;
plot(x,sin(x),'b');
area(x,0.5*sin(x));
set(gca,'xlim',[0,2*pi]);
hgsave('A');
figure; hold on;
plot(x,cos(x),'r');
area(x,0.5*cos(x),'FaceColor','r');
hgsave('B');
%% clear and close all
clear;
close all;
%% copy process
fig1 = openfig('A');
fig2 = openfig('B', 'invisible');
copyobj(get(get(fig2,'children'),'children'), get(fig1,'children'));
close(fig2);
This gives the following result if manually combined in subplots:
Upvotes: 4