ManiAm
ManiAm

Reputation: 1851

Plotting an existing MATLAB plot into another figure

I used the plot command to plot a figure and then changed lots of its properties using set command. I also store the handle of the plot (say h1).

What I need is to use the handle to plot the same figure again later in my code. I checked the plot command and did not find any version that accepts handle. I also thought of getting the Xdata and Ydata and use them to re-plot the same figure.

What is the simplest solution?

Edit 1: A working sample code based on copyobj that PeterM suggested.

hf(1) = figure(1);
plot(peaks);

hf(2) = figure(2);
plot(membrane);

hf(3) = figure(3);
ha(1) = subplot(1,2,1);
ha(2) = subplot(1,2,2);

for i = 1:2
    hc  = get(hf(i),'children');
    hgc = get(hc, 'children');
    copyobj(hgc,ha(i));
end

Edit 2: I also found this function that can copy figures (including legend) into a subplot.

Upvotes: 9

Views: 15932

Answers (5)

ek44uowm
ek44uowm

Reputation: 1

I have used the function figs2subplots (given in Edit2 in the original question) - it does the work and is very easy to use.

Upvotes: 0

Werner
Werner

Reputation: 2557

Improving @PeterM nice answer, one easier way would be:

fig2H=copy(gcf) % or change gcf to your figure handle

But it depends on what you want, if you want only the axes, or the whole figure… (btw, it doesn't seem to copy the legend handle).

Upvotes: 5

Prashanth
Prashanth

Reputation: 1332

This would be the laziest way to accomplish what you want.

% Sample plot
f1 = figure(1);
plot(0:0.1:2*pi, sin(0:0.1:2*pi));
f2 = figure(2);

% The code you need
saveas(f1, 'temp.fig')
f2 = hgload('temp.fig')
delete('temp.fig')

Upvotes: 0

PeterM
PeterM

Reputation: 2702

I have run into this situation before. Depending on what you are trying to do the function copyobj may be appropriate. This function lets you take the contents of one axes and copy it to a new figure.

Upvotes: 5

Oli
Oli

Reputation: 16065

You can use saveas to save the figure in a file, and the open to load the exact same figure from this file.

Upvotes: 1

Related Questions