How to change the order of lines in a Matlab figure?

59,454

Solution 1

If you know the handle of line you want on top (e.g. because you called h = plot(...), you can use uistack

uistack(h,'top')

Alternatively, you can manipulate the order of children of your current axes directly. The following puts the last-most curve on top.

chH = get(gca,'Children')
set(gca,'Children',[chH(end);chH(1:end-1)])

Solution 2

The resolution given by @Jonas using 'Children' property does not work in its given format. It should be modified as follows:

chH = get(gca,'Children')
set(gca,'Children',flipud(chH))

Solution 3

When the image has a legend, the get(gca,...) and set(gca,...) pair result in an error: "Error using set. Children may only be set to a permutation of itself" In that case, I used the GUI select tool of the figure to select the axes objects, then get and set work only with the plots as required and not the legend as well. After calling set, you have to refresh the legend by calling legend(...). I had 5 plots that I needed to reorder. When unsure about the order, permute plots two at a time, refresh the legend and see if that is the order you wanted

Solution 4

The Children property holds the references and the order dictates the graphics stack.

Another option how to retrieve the list is

gcaChildrenList=gca.Children;

This way you can play with the orders like

gca.Children=gca.Children([2:end 1]);         % Put the topmost graphic in the bottom
gca.Children=gca.Children([end:-1:1]);        % Flip the stack
gca.Children=gca.Children([1:N-1 N+1:end N]); % Put Nth graphics ontop the stack

Tested on Matlab R2014b

Share:
59,454
Tobias Kienzler
Author by

Tobias Kienzler

Physicist.

Updated on April 04, 2020

Comments

  • Tobias Kienzler
    Tobias Kienzler about 4 years

    Given a plot of three curves in a .fig file I'd like to add another plot (with hold all and plot), but put it behind one of the already existing curves (i.e. make sure the last original curve stays the foreground one). Can this be achieved without having to extract the plot data and re-plotting?