问题
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