Skip to content
This repository was archived by the owner on Apr 5, 2019. It is now read-only.

Commit 674f5ab

Browse files
committed
Add order consideration for appending
The existing append method assumes that the order of the existing legend entries has not been permuted from the plot order of the axes' Children, and vice-versa. Because of this assumption, the order of the legend strings can diverge from the axes' Children plot order for reasons that are not clear to the user. A union of the two object arrays is taken in order to account for the permutation potential. A stable union of the legend's PlotChildren and the parent Axes' Children will return the object handles existing in the legend, in the order they appear in the legend, followed by the object handles not in the legend, in the order they are rendered in the parent Axes. Add warning when more strings are passed to append than there are legend entries. This warning is consistent with the behavior of legend. See: #11
1 parent 8dd6cc7 commit 674f5ab

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

legtools.m

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,24 @@ function append(lh, newStrings)
5454

5555
% Update legend with line object handles & new string array
5656
newlegendstr = [lh.String newStrings]; % Need to generate this before adding new plot objects
57-
lh.PlotChildren = plothandles;
57+
58+
% Use the union of the parent axes' Children and the legend
59+
% handle's PlotChildren to properly order the legend strings.
60+
% Union(A, B, 'Sorted') will return A concatenated with the
61+
% values of B not in A, so we have the handles associated with
62+
% the existing entries and then the remaining handles in the
63+
% order they are plotted.
64+
lh.PlotChildren = union(lh.PlotChildren, plothandles, 'stable');
65+
66+
if numel(newlegendstr) > numel(lh.PlotChildren)
67+
% MATLAB automatically throws out the extra legend entries
68+
% if the number of strings to be added is larger than the
69+
% number of supported graphics objects that are children of
70+
% the parent axes. legend throws a warning in this case and
71+
% we should too
72+
warning('legtools:append:IgnoringExtraEntries', ...
73+
'Ignoring extra legend entries');
74+
end
5875
lh.String = newlegendstr;
5976
end
6077

0 commit comments

Comments
 (0)