Reordering legend items deletes legend handle - how can I get them back?

1 view (last 30 days)
For the legend of a complex plot, I wish to:
1) reorder the items so that they better match the order of data points in the plot
2) increase the legend marker sizes
2) on its own is easy enough, but I found that 1) involves a step that apparently deletes the icons part of the legends handle. Consider the following MWE:
x1 = randn(1,10);
x2 = randn(1,10);
plot(1:10, x1, 'ko', 1:10, x2, 'bo')
[lh,icons] = legend('x1', 'x2');
neworder = 2:-1:1; % reverse order of items (markers + their text) in the legend, so that this nicely matches the order (when viewing top-down) of plotted elements; the default order is reversed, for some reason
icons(4).MarkerSize = 22; % x1
icons(6).MarkerSize = 22; % x2; this is sometimes icons(3).Children.MarkerSize ?!
lh.AutoUpdate = 'off';
lh.PlotChildren = lh.PlotChildren(neworder);
icons(4).MarkerSize = 22; % attempt to re-set this
[lhNEW,iconsNEW] = findobj(gcf, 'Type', 'Legend');
iconsNEW(6).MarkerSize = 22;
The last command gives
Unrecognized property 'MarkerSize' for class 'matlab.graphics.primitive.Data'.
>> icons(4)
ans =
handle to deleted Data
Getting the handles for the created legend by using findobj doesn't work either:
[lhNEW,iconsNEW] = findobj(gcf, 'Type', 'Legend');
iconsNEW(6).MarkerSize = 22;
No method 'findobj' with matching signature found for class 'matlab.ui.Figure'.

Accepted Answer

Voss
Voss on 25 May 2022
Maybe you will have better luck modifying the order of the lines and their names in the call to legend, rather than reordering the objects in the legend after it is created:
x1 = randn(1,10);
x2 = randn(1,10);
h_line = plot(1:10, x1, 'ko', 1:10, x2, 'bo');
names_line = {'x1', 'x2'};
neworder = 2:-1:1; % reverse order of items (markers + their text) in the legend, so that this nicely matches the order (when viewing top-down) of plotted elements; the default order is reversed, for some reason
[lh,icons] = legend(h_line(neworder),names_line(neworder));
icons(4).MarkerSize = 22;
icons(6).MarkerSize = 22;
  2 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!