MATLAB Answers

How do I prevent the legend from Auto Updating?

506 views (last 30 days)
When I have a legend, and then add another plot to the graph, it is automatically added to the legend. How do I prevent legend from auto updating?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Nov 2018
Edited: MathWorks Support Team on 13 Nov 2018
Starting in R2017a, if a legend is present, it will auto-update with new plots added to the axes.
The legend has been changed so that by default it updates when data is added to or removed from a plot automatically. To prevent this behavior, set the legends "AutoUpdate" property.
Ex:
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)
legend('sin(x)','AutoUpdate','off')
To affect all new legends, set the value on the root level. To affect all legends in a figure:
fig = figure;
set(fig,'defaultLegendAutoUpdate','off');
To exclude an individual plot from the legend, set the "Annotation" property':
p = plot(1:10,'DisplayName','Line Chart');
hold on
s = stem(1:10,'DisplayName','Stem Chart');
hold off
s.Annotation.LegendInformation.IconDisplayStyle = 'off'; % make the legend for step plot off
legend('show')
For more information about this change, refer to the release notes:
Also note that the "default" properties system inherits down the entire graphics hierarchy, as documented here:
One can set the same property on the graphics root and it will apply to all figures in that MATLAB session:
set(groot,'defaultLegendAutoUpdate','off')
The above line can also be added to the MATLAB startup script if the user wants it to apply it to every MATLAB session.

More Answers (2)

Loic Vanel
Loic Vanel on 25 Feb 2021
An alternate easier solution is to use a handle for the legend and turn the AutoUpdate property of the legend off before adding more plots :
plot(x1,y1)
leg = legend('plot1');
set(leg,'AutoUpdate','off')
plot(x2,y2)

Products


Release

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by