I have a figure as shown here, with each color indicating the value of a third variable. I attempted to create a colorbar
with the corresponding colors and values. For this purpose first I get
the Color
of the 'Children'
of the axes as follows:
curves = get(gca, 'Children');
mycolorset = cat(1, curves(:).Color);
Then I realized that the order of the colors (same as the order of the Children
) is reversed compared to the order of plotting. So I had to apply flipud
to the colors to make the correct colormap:
set(gcf, 'Colormap', flipud(mycolorset));
Interesting fact is that Plot Browser shows the curves in the correct order.
Now I want to know, is this a universal feature of all Children
in Matlab to be reversed? Do you know a case that this becomes useful at all?
The Children
of an axes
are ordered such that the children near the beginning are displayed on top of children near the end of the list of children (if the SortMethod
is set to 'childorder'
or if you have just a 2D plot).
If you're dynamically adding multiple 2D plots to an axes
, the default behavior of MATLAB is to place new plot objects on top of old plot objects, therefore they need to be appended to the beginning of the Children
list.
figure;
hold on
plot1 = plot(1:10, 'LineWidth', 10, 'DisplayName', 'plot1');
plot2 = plot(10:-1:1, 'LineWidth', 10, 'DisplayName', 'plot2');
legend([plot1, plot2])
get(gca, 'Children')
% 2x1 Line array:
%
% Line (plot2)
% Line (plot1)
If you want to alter which plot is displayed on top of which, you can modify the ordering of the Children
or you can just use the handy uistack
command to do this for you.
set(gca, 'Children', flipud(get(gca, 'Children'))) % Or uistack(plot1, 'top')
get(gca, 'Children')
% 2x1 Line array:
%
% Line (plot1)
% Line (plot2)
This stacking behavior isn't just limited to plot objects in axes
. You can alter the Children
ordering on most UI elements (including uipanels
, figures
, etc.) to determine the visual stacking of the elements.