MATLAB Language Undocumented Features Appending / adding entries to an existing legend


Existing legends can be difficult to manage. For example, if your plot has two lines, but only one of them has a legend entry and that should stay this way, then adding a third line with a legend entry can be difficult. Example:

hold on
legend sin  % Add only a legend entry for sin
hTan = fplot(@tan);  % Make sure to get the handle, hTan, to the graphics object you want to add to the legend

Now, to add a legend entry for tan, but not for cos, any of the following lines won't do the trick; they all fail in some way:

legend tangent  % Replaces current legend -> fail
legend -DynamicLegend  % Undocumented feature, adds 'cos', which shouldn't be added -> fail
legend sine tangent  % Sets cos DisplayName to 'tangent' -> fail
legend sine '' tangent  % Sets cos DisplayName, albeit empty -> fail

Luckily, an undocumented legend property called PlotChildren keeps track of the children of the parent figure1. So, the way to go is to explicitly set the legend's children through its PlotChildren property as follows:

hTan.DisplayName = 'tangent';  % Set the graphics object's display name
l = legend;
l.PlotChildren(end + 1) = hTan;  % Append the graphics handle to legend's plot children

The legend updates automatically if an object is added or removed from its PlotChildren property.

1 Indeed: figure. You can add any figure's child with the DisplayName property to any legend in the figure, e.g. from a different subplot. This is because a legend in itself is basically an axes object.

Tested on MATLAB R2016b