如何防止图例在 R2017a 及更高版本中更新?

How to prevent the legend from updating in R2017a and newer?

自 MATLAB R2017a 起,向坐标区添加绘图时图窗图例会自动更新。以前,可以这样做:

data = randn(100,4);
plot(data)
legend('line1','line2','line3','line4')
hold on
plot([1,100],[0,0],'k-')

用图例绘制四条数据线,然后为 y=0 添加一条黑线。然而,从 R2017a 开始,这导致黑线被添加到图例中,名称为 "data1".

如何防止将此行添加到图例中,以便代码的行为与旧版本的 MATLAB 中的行为相同?

到目前为止,我在 Stack Overflow 上找到的唯一解决方案是 。语法不漂亮:

h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
set(get(get(h,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');

MATLAB R2017a 的发行说明mention this change,并提供了 4 种不同的处理方式。这两种方法最容易放入现有代码中:


1: 在添加黑线之前关闭图例的自动更新。这可以在创建时完成:

legend({'line1','line2','line3','line4'}, 'AutoUpdate','off')

或之后:

h = findobj(gcf,'type','legend');
set(h, 'AutoUpdate','off')

您还可以更改所有未来图例的默认值:

set(groot,'defaultLegendAutoUpdate','off')

2: 关闭不想添加到图例中的黑线的句柄可见性:

plot([1,100],[0,0],'k-', 'HandleVisibility','off')

这里也显示了IconDisplayStyle方法。然而,他们使用点符号,这使得语法更漂亮:

h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
h.Annotation.LegendInformation.IconDisplayStyle = 'off';