how to copy a figure with a figure inside it using Matlab?

26 Ansichten (letzte 30 Tage)
Yang Li
Yang Li am 30 Mär. 2022
Kommentiert: Yang Li am 30 Mär. 2022
Hi all, I am trying to make a figure with two subplots, and each subplot has two components- a main figure (i.e., large) and a figure within it (i.e., small). But when I use copyobj() to get the final figure, it only copys two small figures together. Any ideas will be greatly appreciated.
Here is a toy script, and you can see that the figure 3 only contains the small figures in figure 1 and 2.
clc
clear
close all
% figure 1
x1 = linspace(0,1);
x2 = linspace(3/4,1);
y1 = sin(2*pi*x1);
y2 = sin(2*pi*x2);
figure(1)
plot(x1,y1)
axes('Position',[.6 .6 .2 .2])
box on
plot(x2,y2)
% figure 2
x3 = linspace(0,2);
x4 = linspace(3/5,1);
y3 = sin(3*pi*x1);
y4 = sin(2.5*pi*x2);
figure(2)
plot(x3,y3)
axes('Position',[.43 .6 .2 .2])
box on
plot(x4,y4)
% final figure
ax = zeros(2,1);
for i = 1:2
h = figure(3)
h.Position = [10 10 1000 2000];
ax(i) = subplot(2,1,i);
copyobj(allchild(get(figure(i),'CurrentAxes')),ax(i),'legacy');
end
Fig 1 and Fig 2
Fig.3
Thanks!

Akzeptierte Antwort

Dave B
Dave B am 30 Mär. 2022
I think you just copied the small axes into the same position, making them into big axes (and putting them on top). In other words you're using subplot to determine the size where the new axes go, but you don't really want them to go there (well you want one to go there and one to go somewhere else).
You could do some math and set the Position values directly (i.e. the offset to the other axes), or you could take this shortcut and just use uipanel for the top half and bottom half:
% figure 1
x1 = linspace(0,1);
x2 = linspace(3/4,1);
y1 = sin(2*pi*x1);
y2 = sin(2*pi*x2);
figure(1)
plot(x1,y1)
axes('Position',[.6 .6 .2 .2])
box on
plot(x2,y2)
% figure 2
x3 = linspace(0,2);
x4 = linspace(3/5,1);
y3 = sin(3*pi*x1);
y4 = sin(2.5*pi*x2);
figure(2)
plot(x3,y3)
axes('Position',[.43 .6 .2 .2])
box on
plot(x4,y4)
%%
f1 = figure(1);
f2 = figure(2);
figure(3);
ptop = uipanel('Position',[0 .5 1 .5],'BorderType','none');
copyobj(f1.Children,ptop);
pbot = uipanel('Position',[0 0 1 .5],'BorderType','none');
copyobj(f2.Children,pbot);

Weitere Antworten (0)

Kategorien

Mehr zu Interactive Control and Callbacks finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by