Copy a figure to a subplot including all elements

173 views (last 30 days)
I have a moderately complex plot that I produce regularly, for various purposes, and I have therefore put generation of that plot into a function.
I now have an application where I need to show a grid of these plots - so I need to take the figure produced by the function and put it into a subplot.
The closest approach to this that I've found so far, from some googling, is,
copyobj(allchild(get(figurehandle, 'CurrentAxes')), subplotaxeshandle);
This serves to copy the actual graph, but omits axis labels, title, etc., as they are not children of the axes. It's worse if it's a polar plot, as it also doesn't bring across axis properties like ThetaDir or ThetaZeroLocation.
I guess that I could probably work out how to find the handles for those things and copy them manually, like above, but that loses much of the benefit of abstracting the figure production to a function in the first place. Surely there must be a better way?
Thanks

Answers (1)

Bruno Luong
Bruno Luong on 22 Aug 2019
Edited: Bruno Luong on 22 Aug 2019
close all
fig1 = figure(1);
ax = axes('parent',fig1);
h=plot(ax,rand(1,10));
xlabel(ax,'x');
ylabel(ax,'y');
title(ax,'source');
fig2 = figure(2);
ax1 = subplot(2,2,1,'parent',fig2);
ax2 = subplot(2,2,2,'parent',fig2);
ax3 = subplot(2,2,3,'parent',fig2);
ax4 = subplot(2,2,4,'parent',fig2);
axcp = copyobj(ax, fig2);
set(axcp,'Position',get(ax1,'position'));
delete(ax1);
  5 Comments
Marco Riani
Marco Riani on 27 Mar 2020
Is the instruction 'parent',fig2 in
ax1 = subplot(2,2,1,'parent',fig2);
ax2 = subplot(2,2,2,'parent',fig2);
ax3 = subplot(2,2,3,'parent',fig2);
ax4 = subplot(2,2,4,'parent',fig2);
necessary?
Similarly, can ax = axes('parent',fig1); be replaced by ax = axes(fig1);
Walter Roberson
Walter Roberson on 13 Apr 2020
Bruno writes careful code. He knows that even though the code might have just selected figure 1 or figure 2, that that does not mean that on the next line or a line after that, that that figure is still the selected figure.
  • if a callback of any kind executes, the "current" figure or "current" axes can change due to code executed in the callback
  • If the use drops into the debugger, then if the user clicks anywhere on a figure to drag the figure out of the way or resize it so that they can see the editor window or the command window, then that figure will become the "current" figure.
Being explicit about which object the graphics is to be applied to is good safety programming. And in some cases when you explicitly pass in the parent to act against, that prevents the parent from being automatically reset or even deleted by graphics routines that are trying to be helpful.
I suggest you search for tag:always-parent to read some of my postings.

Sign in to comment.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!