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

26 次查看(过去 30 天)
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!

采纳的回答

Dave B
Dave B 2022-3-30
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by