將新增條目新增到現有圖例

現有的傳說可能難以管理。例如,如果你的繪圖有兩行,但只有一行有一個圖例條目,並且應該保持這種方式,那麼新增帶有圖例條目的第三行可能很困難。例:

figure
hold on
fplot(@sin)
fplot(@cos)
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

現在,要為 tan 新增一個圖例條目,但不為 cos 新增,以下任何一行都不會起作用; 他們都以某種方式失敗了:

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
legend(f)

幸運的是,一個名為 PlotChildren 的無證傳奇屬性跟蹤了父母 1 的孩子。因此,要採用的方法是通過 PlotChildren 屬性顯式設定圖例的子項,如下所示:

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

如果在 PlotChildren 屬性中新增或刪除物件,則圖例會自動更新。

1 確實:數字。你可以將具有 DisplayName 屬性的任何圖形的子項新增到圖中的任何圖例,例如,從不同的子圖。這是因為圖例本身基本上是一個軸物件。

在 MATLAB R2016b 上測試