Why does legend highlight the wrong colors with lineplot?
Show older comments
Hey everyone,
I want to highlight specific lines in a plot and I found a weird behaviour in Matlab 2019b. If I plot them using a logical index, the legend does not color the correct lines.
Here is a Minimal Working Example:
clc
clear
n = 10;
t = 20;
tt = rand(t,n);
legstr = cellstr(string(('a':'z').').');
ind1 = ones(1,n); % all elements except 2nd and 5th
ind1(2) = 0;
ind1(5) = 0;
ind1 = logical(ind1);
ind2 = zeros(1,n); % second element only
ind2(2) = 1;
ind2 = logical(ind2);
ind3 = zeros(1,n); % 5th element only
ind3(5) = 1;
ind3 = logical(ind3);
% plot all elements except 2nd and 5th
plot(tt(:,ind1),'Color',0.6*ones(1,3))
hold on
% plot 2nd
plot(tt(:,ind2),'Color','r')
% plot 5th
plot(tt(:,ind3),'Color','b')
hold off
legend(legstr(1:n))
The above code generates a matrix called tt, which has 20 elements and 10 variables (called n). I want to plot them all but highlight the second and the fith variable. So I create an index for those, plot all except 2nd and 5th and then plot those individually, However, the legend highlights the last two, which is wrong.

If I plot all of tt (uncomment line 8 and 9) the legend is all gray.
This is a MWE, in the original code there is more going on, so I just used shortcuts to recreate the problem.
Accepted Answer
More Answers (0)
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!