refreshing legend when Visible is set on/off

hello
I would like to know if there is a way to refresh automatically a legend when the visibility of a line is set on/off.
I have several lines plotted and I switch their visibilities using the command:
set(handle,'Visible','on')
% or set(handle,'Visible','off')
which doesn't seem to be taken into account by the ''-DynamicLegend' function.
However right-clicking on the refresh function works correctly
Thank you for your answer
Ewen.

5 Comments

What is the DynamicLegend function?
sorry it's not a function but a legend property.
the command:
legend('-DynamicLegend');
set the auto-refresh of a legend when a new plot is added or deleted in the figure.
I don't see such option in the documentation.
try
h(1)=plot(0:0.1:1,0:0.1:1,'red','DisplayName','redline')
legend('-DynamicLegend');
pause(1)
hold on
h(2)=plot(0:0.1:1,0:10,'b','DisplayName','blueline')
pause(1)
h(3)=plot(0:0.1:1,0:0.01:0.1,'g','DisplayName','greenline')
pause(1)
delete(h(1))
for exemple
I tried to dwell in C:\Program Files\MATLAB\R2012a\toolbox\matlab\scribe\@scribe\@legend\init.m, but have not got very far.
You should ask Technical Support.

Sign in to comment.

Answers (2)

Here is the gist of it:
hLegend = findall(gcf,'tag','legend');
uic = get(hLegend,'UIContextMenu');
uimenu_refresh = findall(uic,'Label','Refresh');
callback = get(uimenu_refresh,'Callback');
hgfeval(callback,[],[]);
I did not observe anything unusual with your code. It plotted the red, green, and blue lines and added the legend immediately after plotting, and then when you deleted the red line, the red legend automatically vanished. This is in R2011b. What version are you running? Maybe it was a bug that got fixed.
One thing you might try is to add a "drawnow" after your calls to plot() to force an update/refresh of the figure.

3 Comments

The legend doesn't "update" when you set the line to 'Visible','Off'.
It would be nice to leave the string entry in the legend but make the line invisible or erase the entry from the legend completely.
Oh, you're right. I just blindly ran the script he gave and didn't notice that he didn't have the line of code in there that demonstrated what he wanted to demonstrate.
you're right, i should have added the line:
pause(1)
set(h(3),'Visible','off').

Sign in to comment.

Asked:

on 5 Apr 2012

Community Treasure Hunt

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

Start Hunting!