How to resize a subplot copied to a new figure using CopyObj

12 vues (au cours des 30 derniers jours)
Lina Koronfel
Lina Koronfel le 8 Oct 2021
Commenté : Dave B le 8 Oct 2021
It seems easy but I don't seem to find a straight forward preivous answer to my question. I want to copy a subplot from a parent figure of 3 subplots to a new figure of only 2 subplots, however I don't know how to resize the copied subplot such that it fits a a figure of only 2 subplots (please see attached image for reference). Please help!!
I simply used the copyobj function but I don't know hwo to adjust the size:
NewFig=figure;
p(1)=subplot(2,1,1)
%generate subplot 1
p(2)=subplot(2,1,2)
subplot(2,1,2);
copyobj(p(OldFig),NewFig);

Réponse acceptée

Dave B
Dave B le 8 Oct 2021
Modifié(e) : Dave B le 8 Oct 2021
This is way easier with tiledlayout and nexttile. With subplot, you can't very easily swap axes: you can use the positions of some blank axes in the new 2 plot figure, but subplot adjusts the plots to align the inner positions based on the labels etc. and things go wrong if those labels take up a lot of space. You can adjust to re-align things (really you're doing the work subplot would normally do) but it's hard to generalize that logic.
Here's how this works with tiledlayout:
f1=figure(1);
tiledlayout(f1,1,3)
a=nexttile;plot(rand(3))
b=nexttile;bar(1:10)
xlabel({'this' 'is' 'a' 'long' 'label'})
nexttile;imagesc(magic(5))
f2=figure(2);
t2=tiledlayout(f2,1,2);
copyobj(a,t2)
copyobj(b,t2)
With subplot this would be trouble, because of the long xlabel, so you'd have to do some work to tweak positions (but generalizing this is quite difficult:
f3=figure(3);
aa=subplot(1,3,1);plot(rand(3))
bb=subplot(1,3,2);bar(1:10)
xlabel({'this' 'is' 'a' 'long' 'label'})
subplot(1,3,3);imagesc(magic(5))
f4=figure(4);
km=subplot(1,2,1);
cc=copyobj(aa,f4);
cc.OuterPosition=km.OuterPosition;
delete(km);
km=subplot(1,2,2);
dd=copyobj(bb,f4);
dd.OuterPosition=km.OuterPosition;
delete(km)
%not quite right...match the Y and HEIGHT of the second axes
cc.InnerPosition([2 4])=dd.InnerPosition([2 4]);
One last note - you can even copy an old subplot into a new tiledlayout, just set the Layout.Tile property:
f5 = figure(5);clf
t3 = tiledlayout(f5,1,2);
aaa=copyobj(aa,t3);
bbb=copyobj(bb,t3);
bbb.Layout.Tile=2;
  2 commentaires
Lina Koronfel
Lina Koronfel le 8 Oct 2021
Thank you for the response. This worked like magic!!
Just for info: This is not applicable to version 2019a. I had to upgrade in order to use the tiledlayout function.
Dave B
Dave B le 8 Oct 2021
Ah sorry, yes you were right on the cusp as tiledlayout started in 2019b...glad it helped!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by