matlabuser-interfacematlab-figurematlab-guide

Is there a way to change the current axes object in matlab without affecting the uistack ordering?


Matlab provides a function called uistack for arranging UI objects in the depth direction (which objects are in front of which others, etc). There is also a function (axes) for setting the current axes. I find that when I call axes, it also automatically puts that axes object in front of all other objects (including uipanels, etc). Is there any way to avoid this?

Here is some code that illustrates my question:

figure(1)
clf

ax1 = axes();
set(ax1,'position',[.1 .1 .5 .5],'xtick',[],'ytick',[],'color','r')

ax2 = axes();
set(ax2,'position',[.3 .3 .5 .5],'xtick',[],'ytick',[],'color','b')

% blue (ax2) is on top since it was created after ax1

uistack(ax1,'top')

% red (ax1) is now on top (good)

axes(ax2)

% [do some plotting or something in ax2]

% blue (ax2) is now on top (I'd rather avoid this)

Solution

  • To make h_ax the current axes in figure h_fig without putting those axes in front, use:

    set(h_fig, 'CurrentAxes', h_ax)
    

    Why this works

    From the documentation of the axes function, the syntax axes(cax)

    makes cax the first object listed in the Children property of the figure and sets the CurrentAxes property of the figure to cax.

    Making cax the first object listed in the Children property is what causes it to be in front. This can be checked by modifying that property and seeing the effect. Also, by looking at uistack's code it is seen that what that function internally does it to rearrange the order of the figure's Children.

    Setting the figure's CurrentAxes property to cax is what causes those axes to be the current ones. This can be checked by modifying that property, plotting something and seeing in what axes the plot appears.

    So, setting the CurrentAxes property of the figure to the desired axes achieves the desired effect without moving those axes to the front.