legend() has an issue with 'Selected' or 'selected'

10 views (last 30 days)
The command legend() has an issue with 'Selected' as a legend name.
E.g.:
t = -13:13;
A = t*2-3*t;
B = A(A>0);
figure
plot(t, A, 'r-'), hold on
ts = t(A>0);
plot(ts, B, 'ko'), grid on
legend('All data', 'selected')
The above code prompts the following error:
Error using legend (line 272)
Mismatched number of name-value pair arguments. Specify a property
value for each property name.
Error in Untitled8 (line 8)
legend('All data', 'selected')
---
Any comments or suggestions how to address this issue is appreciated.
Thank you.

Accepted Answer

Cris LaPierre
Cris LaPierre on 20 Feb 2021
Edited: Cris LaPierre on 20 Feb 2021
The problem here is that 'selected' is being interpreted as the name of a name-value pair.
Change you legend labels to a cell array of character vectors to remove the ambiguity.
t = -13:13;
A = t*2-3*t;
B = A(A>0);
figure
plot(t, A, 'r-'), hold on
ts = t(A>0);
plot(ts, B, 'ko'), grid on
legend({'All data', 'selected'})
  3 Comments
Steven Lord
Steven Lord on 20 Feb 2021
Another way to handle this is to set the DisplayName property of the objects that you want to appear in the legend.
% Make some sample data
x = 0:360;
y1 = sind(x);
y2 = cosd(x);
% Set up the axes
axis([0 360 -1 1])
hold on
% Plot
plot(x, y1, 'ro-', 'MarkerIndices', 1:30:numel(x), 'DisplayName', 'Selected')
plot(x, y2, 'kx--', 'MarkerIndices', 15:30:numel(x), 'DisplayName', 'MarkerIndices')
% Show the legend
legend show
I set the MarkerIndices property as well so I could show a subset of the points that were plotted as markers. Even though that's a property of the plotted line I could still use it as the DisplayName.
Sulaymon Eshkabilov
Sulaymon Eshkabilov on 20 Feb 2021
Thanks - Steven. This is a very nice syntax.

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Object Properties in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!