recipes : Plotting : Plot Manipulation : Altering the order of plot elements

Problem

How do I place a plot element behind another?

Solution

The most recently added plot element always appears on top of previous ones. This can be altered after the event by altering the order of the objects in the axes' "children" property.

%Make a plot with red markers beneath a black line

d=1:10; %The data we will plot

clf

hold on
plot(d,d,'or','MarkerFacecolor','r')
plot(d,d,'k-','linewidth',3)
hold off

xlim([1,10])
ylim([1,10])
%Switch the plot order so the markers lie over the line

c=get(gca,'Children'); %Get the handles for the child objects from the current axes
set(gca,'Children',flipud(c)) %Invert the order of the objects

Discussion

Of course it is easier to simply plot the ojects in the reverse order from that which you would have them appear. When this isn't possible, manipulating the order of the handles is a good way of getting the effect you want.

In the above example, flipud simply inverts the order of the vector which contains a list of axis handles of the axis children. There are just two in this case, but on a more elaborate plot there may be many. One can exert fine control over how the plot looks by manipulating the order of the elements in the variable c.