Why does legend highlight the wrong colors with lineplot?

5 views (last 30 days)
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

Florian Bidaud
Florian Bidaud on 14 Aug 2023
Edited: Florian Bidaud on 14 Aug 2023
This is because you plot these two curves in last. Legend is affected to the order of the plots, legend{1} is first plot, legend{2} is second plot, legend{3} is third plot etc.
You can either :
  • Change the order in the legend cell array: legstr = {'a' 'c' 'd' 'f' 'g' 'h' 'i' 'j' 'b' 'e'}
  • or change the order of plotting, like plotting the 1st curve, then the 2nd (highlighted), then 3rd and 4th, then 5th (highlighted), then 6th to last.
It is quite straightforward to do with the index numbers of your highlighted curves.
Something like that should work:
clear
n = 10;
t = 20;
tt = rand(t,n);
legstr = cellstr(string(('a':'z').').');
ind2 = 2;
ind3 = 5;
figure
hold on
for i = 1:ind2-1
plot(tt(:,i),'Color',0.6*ones(1,3))
end
plot(tt(:,ind2),'Color','r')
for i = ind2+1:ind3-1
plot(tt(:,i),'Color',0.6*ones(1,3))
end
plot(tt(:,ind3),'Color','b')
for i = ind3+1:n
plot(tt(:,i),'Color',0.6*ones(1,3))
end
legend(legstr)
  1 Comment
Boris Blagov
Boris Blagov on 15 Aug 2023
I see. I have to see how to implement this in my code, which is more convoluted.
Thanks!

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!