From: Mayi DA on
Dear all,
When setting a new color to a plot line, the legend color can update automatically. However, if you delete a plot line, the legend does not change anything, how to update legend?
hf = figure(1);
hp=plot(rand(10,2));
legend('data1','data2');
% now you can see that two plot line with legend 'data1' and 'data2'

% continue to run:
delete(hp(1));
% the first plot line was removed but the legend does not change.

best regards
mayi
2010-07-20
From: Ross on
"Mayi DA" <damayi(a)gmail.com> wrote in message <i245be$a0r$1(a)fred.mathworks.com>...
> Dear all,
> When setting a new color to a plot line, the legend color can update automatically. However, if you delete a plot line, the legend does not change anything, how to update legend?
> hf = figure(1);
> hp=plot(rand(10,2));
> legend('data1','data2');
> % now you can see that two plot line with legend 'data1' and 'data2'
>
> % continue to run:
> delete(hp(1));
> % the first plot line was removed but the legend does not change.
>
> best regards
> mayi
> 2010-07-20

I think Yair Altman has a nice answer here: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/

For example:

x=0:.01:10;
h1=plot(x, sin(x), 'DisplayName','sin');
legend('-DynamicLegend');
hold all; % add new plot lines on top of previous ones

%now add a line and the legend should update
h2=plot(x, cos(x), 'DisplayName','cos');

%now remove a line and the legend should update again
delete(h1)

Ross