【问题标题】:How to prevent the legend from updating in R2017a and newer?如何防止图例在 R2017a 及更高版本中更新?
【发布时间】:2019-12-12 02:23:25
【问题描述】:

自 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 上找到的唯一解决方案是 remove the legend item after it has been added。语法不漂亮:

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

【问题讨论】:

    标签: matlab plot matlab-figure legend


    【解决方案1】:

    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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-26
      • 2021-11-17
      • 2014-07-05
      • 1970-01-01
      • 2015-03-04
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多