How to stop legend from adding 'data1', 'data2' when additional data is plotted
Show older comments
In 2017a, when I make some plots and add a legend, then add subsequent plots, the legend is updated with new unwanted entries generically labeled 'data1', 'data2', etc. How can I "freeze" the legend so it does not update? I am not able to re-run the legend command after all plots are drawn because the legend is generated within a function, and the additional lines are plotted at the command line. I can't easily regenerate the legend from the command line because the real plot is complicated, but if there is a way to manually edit the legend command and delete the 'data1' and 'data2' lines and labels, that would work.
figure;
h1 = plot(rand(1,7), rand(1,7));
hold on;
h2 = plot(rand(1,7), rand(1,7));
h3 = plot(rand(1,7), rand(1,7));
% We only want legend entries for the first three lines
lh = legend([h1 h2 h3], ...
'First line', 'Second line', 'Third line');
pause; % This is the legend as it should appear
% Additional lines
h4 = plot(rand(1,7), rand(1,7));
h5 = plot(rand(1,7), rand(1,7));
% Undesired legend entries appear for additional lines
% labeled 'data1' and 'data2'

Accepted Answer
More Answers (1)
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!