Browsed by
Tag: Shaded Regions

Removing Items for Plot Legends

Removing Items for Plot Legends

In this tutorial, an object will be removed from a plot legend with the use of the hasbehavior command. Often when creating plots, annotations or trivial lines may be included which can be distracting when included on a legend. For this tutorial, an RLC circuit is simulated and a shaded region is included ± 0.1 A to communicate a convergence region. We will remove this shaded region from the plot legend while keeping the object on the plot.

For the lines that we desire remain on the legend, we will assign the line name through he DisplayName property for the line handle. A DisplayName can also be assigned during plotting using the DisplayName property as follows: plot(x,y, ‘DisplayName’, ‘Desired Name’).

% Now lets assign names to each line
for ii = 1:length(zeta)
    h1(ii).DisplayName = ['\zeta = ' num2str(zeta(ii))];
end

Full_Legend

The first legend entry will be removed using the hasbehavior command. Note: the Shaded_Handle variable represents the line handle associated with handle assigned to the shaded object, which was assigned on line 26 of the full source code.

% Remove the first legend entry associated with the A2 handle
hasbehavior(Shaded_Handle,'legend',false);
legend('show');

Now, when we toggle the legend, the legend entry for the shaded region is removed and only the lines remain.

Truncated_Legend

% RLC Coefficients & Solution
C = 1;
L = 1;
R = .5;

t = linspace(0,20,100);
zeta = 0.4:.2:0.8;
I = zeros(length(zeta), length(t));
ii = 1;
for jj = 1:length(zeta)
    w0 = 1/sqrt(L*C);
    wd = w0*sqrt(1-zeta(jj)^2);
    B2 = 5;
    B1 = 0;
    I(ii,:) = B1*exp(-alpha*t).*cos(wd*t) +...
        B2*exp(-alpha*t).*sin(wd*t);
    ii = ii + 1;
end

% Create Figure
figure();
hold('on');
grid('on');
xlabel('Time (s)'); ylabel('Current (A)');
h1 = plot(t, I, 'LineWidth', 2);
Shaded_Handle = patch([0, 20, 20, 0], [0.1, 0.1, -0.1, -0.1],...
    'blue', 'LineStyle', 'none', 'FaceAlpha', 0.5);
uistack(Shaded_Handle, 'bottom'); % Move Shaded_Handle to bottom

% Now lets assign names to each line
for ii = 1:length(zeta)
    h1(ii).DisplayName = ['\zeta = ' num2str(zeta(ii))];
end

% Remove the first legend entry associated with the A2 handle
hasbehavior(Shaded_Handle,'legend',false);
legend('show');