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

陌路散爱 提交于 2020-04-06 03:48:33

问题


Since MATLAB R2017a, figure legends update automatically when adding a plot to axes. Previously, one could do this:

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

to plot four data lines with a legend, and then add a black line for y=0. However, since R2017a, this leads to the black line being added to the legend, with the name "data1".

How do I prevent this line from being added to the legend, so that the code behaves like it did in older versions of MATLAB?

The only solution I have found so far on Stack Overflow is to remove the legend item after it has been added. The syntax is not pretty:

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

回答1:


The release notes for MATLAB R2017a mention this change, and provide 4 different ways of handling the situation. These two methods are easiest to put into existing code:


1: Turn off auto updating for the legend before adding the black line. This can be done at creation time:

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

or after:

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

You can also change the default for all future legends:

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

2: Turn off handle visibility for the black line that you don't want added to the legend:

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

The IconDisplayStyle method is also shown here. However, they use the dot notation, which makes the syntax is a bit prettier:

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


来源:https://stackoverflow.com/questions/57343725/how-to-prevent-the-legend-from-updating-in-r2017a-and-newer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!