How can I copy a figure that includes a colorbar to another figure

19 views (last 30 days)
I am trying to copy multiple figures to subplots in a new figure. It works for most figures, but it is giving errors for any figures that contain a colorbar or legend. What do I have to do to successfully copy all elements of every figure?
Below is a script that I use to test. The first and second figures copy ok. When the third figure, which includes a colorbar is included, I receive the error "Error using copyobj Invalid child handle argument". If I exclude the colorbar from the third figure, then the third figure is copied without error.
Somehow the handle to the colorbar is not working with the copyobj function; what should I do to fix this?
close all
x1 = (1:10);
y1 = x1;
x2 = (10:100);
y2 = 5*x2.^2 - 7.*x2;
z = peaks(25);
title(' My First Figure')
xlabel('Time (s)')
ylabel('F (N)')
title(' My Second Figure')
xlabel('Velocity (m/s)')
ylabel('Time (s)')
title(' My Third Figure')
xlabel('Position (mm)')
ylabel('Position (mm)')
zlabel('Height (\mum)')
colorbar % The copying fails if this is included. Comment this out and it works.
% Copy the three existing figures to subplots in a new figure
figHandles = get(0, 'Children');
figCount = length(figHandles);
figParent = figure;
rowCount = 2;
colCount = 2;
for i=1:figCount
% create a new subplot in the new figure, and save it's handle
hSubplotDestFig = subplot(rowCount,colCount,i,'parent',figParent);
% copy all children of the original figure to the subplot that
% was just created
hAxesOrig = findobj(figHandles(i),'type','axes');
axesChildrenOrig = get(hAxesOrig,'children');
dpb on 5 Oct 2022
I played around with some time in the past and ran into an impasse on subplots because the colorbar and legend are children of the figure, not the axes and there's no separate object handle to constrain them to fit within the axes or be positioned to the axes when they're subplots.
The only kludge I found wasn't all that satisfactory was to have a set of 'Position' values for each subplot and reset the next axes to match the desired -- I was able with much difficulty to recreate a specific set, but it was not a pretty exercise and gave it up as a lost cause in general.
The only example actually given simply redraws the colorbar after copying the axes; I'm guessing that is the better part of valor here as well. There are some corners in HG2 that simply aren't accessible in straightforward manner.

Sign in to comment.

Answers (0)




Community Treasure Hunt

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

Start Hunting!