how to put legend in plot selectively in matlab

To put legend selectively in a plot in Matlab with visibility control, you can follow these steps:

  1. First, create a plot with multiple lines/curves/styles.
  2. Call the legend function with all the line handles and legend titles as inputs. Use ,'AutoUpdate','off' to prevent automatic updates of the legend.
  3. Use the set function with the 'Visible' property to selectively hide/show certain legend entries.

Here is an example code:

main.m
% create a plot with multiple lines
x = 1:10;
y1 = x;
y2 = x.^2;
y3 = x.^3;
plot(x, y1, '-r', x, y2, ':b', x, y3, '--g');

% add a legend with all entries
legend('y1', 'y2', 'y3', 'AutoUpdate', 'off');

% selectively hide/show certain entries
set(get(get(gca,'Annotation'),'LegendInformation'),...
    'IconDisplayStyle','off','Visible','off'); % turn off all entries

set(findobj(gca,'Type','line','Color',[1 0 0]),...
    'HandleVisibility','on','DisplayName','y1'); % turn on y1 entry
set(findobj(gca,'Type','line','Color',[0 0 1],'LineStyle',':'),...
    'HandleVisibility','on','DisplayName','y2'); % turn on y2 entry

% refresh and update the legend
legend('show');
672 chars
22 lines

In this example, we create a plot with y1, y2, and y3 lines using different styles. Then, we add a legend with all entries and turn off automatic updates. Finally, we use set function to selectively hide all entries and show only y1 and y2. We refresh and update the legend with 'show' option.

gistlibby LogSnag